Amy*_*yth 28 javascript angularjs
我有一个对象数组如下.
$scope.students = [{'isSelected': true},
{'isSelected': true},
{'isSelected': false},
{'isSelected': true},
{'isSelected': true},
]
Run Code Online (Sandbox Code Playgroud)
如何获取isSelected属性设置为的计数项true?
问题是$scope.students从REST api获取并简单地循环遍历$ scope.students变量不起作用,undefined直到请求完成,因此循环代码错误说出来$scope.students is not defined.
我尝试过使用$watch但在这种情况下我必须在watch指令下定义循环,它只在$ scope.students定义时才有效,之后循环不起作用$ scope.students本身没有改变.
Sam*_*ari 27
还有另一种方法:AngularJS过滤器.你可以这样写:
var selectedCount = $filter('filter')($scope.students, { isSelected: true }).length;
Run Code Online (Sandbox Code Playgroud)
Tim*_*olo 17
你也可以使用JavaScript过滤方法(见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
$scope.selectedStudentsCount = function() {
return $scope.students.filter(function(obj){return obj.isSelected}).length;
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*Tom 16
您可以将以下方法添加到控制器.selectedStudentsCount范围中的变量将保留所有选定学生的数量(isSelected设置为的位置true).
功能计数选定的用户中angular.forEach只有将被执行students不为空.否则为空 students变量selectedStudentsCount将返回0.
$scope.selectedStudentsCount = function() {
var count = 0;
angular.forEach($scope.students, function(student){
count += student.isSelected ? 1 : 0;
});
return count;
}
Run Code Online (Sandbox Code Playgroud)
请注意,这selectedStudentsCount是一个函数,因此必须()在模板中调用,例如
<h2>Total selected students: {{selectedStudentsCount()}}</h2>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32315 次 |
| 最近记录: |