我在Angular JS中有一个应用程序,我试图弄清楚如何将两个字符计数长度(从文本区域输入)添加到一起,如下所示,但这不起作用:
$scope.what=[];
$scope.why=[];
$scope.characters = $scope.what.length + $scope.why.length;
我做错了什么?
答案 0 :(得分:2)
characters
应该是一个功能:
$scope.characters = function(){
return $scope.what.length + $scope.why.length;
}
然后在HTML /视图中调用函数:
{{ characters() }}
characters
对象在构建时初始化并保持静态的方式设置它。
答案 1 :(得分:0)
更新textarea值时,您必须更新字符的值,一种方法是使用像
这样的手表
var app = angular.module('my-app', [], function() {})
app.controller('AppController', function($scope) {
$scope.message = "Welcome";
$scope.what = '';
$scope.why = '';
$scope.$watch('[what, why]', function() {
console.log('x')
$scope.characters = $scope.what.length + $scope.why.length;
})
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
<textarea ng-model="what"></textarea>
<textarea ng-model="why"></textarea>
<p>{{characters}}</p>
</div>
答案 2 :(得分:0)
另一个更好的ES5属性getter方法应该比其他观察器功能更好:
angular.module('demo', []).controller('MainCtrl', function($scope) {
$scope.what = '';
$scope.why = '';
Object.defineProperty($scope, 'characters', {
get() {
return $scope.what.length + $scope.why.length;
}
});
});
<script src="https://code.angularjs.org/1.4.3/angular.js" ></script>
<div ng-app="demo" ng-controller="MainCtrl">
<input type="text" ng-model="what"> <input type="text" ng-model="why">
<div>{{characters}}</div>
</div>