获取数组中具有某些属性的项目数 [英] get count of items with some property in an array
问题描述
我有一个对象数组,如下所示.
$scope.students = [{'isSelected': true},{'isSelected': true},{'isSelected': false},{'isSelected': true},{'isSelected': true},]
如何获得 isSelected
属性设置为 true
的计数项目?
更新:
问题是 $scope.students
是从 REST api 获取的,并且简单地循环遍历 $scope.students 变量不起作用,因为该变量是 undefined
,直到请求已完成,因此循环代码出错,说 $scope.students 未定义
.
我尝试使用 $watch
但在那种情况下我必须在 watch 指令下定义循环,并且它只在定义 $scope.students 时工作一次,之后循环不起作用因为 $scope.students 本身并没有改变.
您可以将以下方法添加到您的控制器中.您范围内的变量 selectedStudentsCount
将保留所有 选定学生的数量(其中 isSelected
设置为 true
).
students
不为空时,才会执行 angular.forEach
中的 selected users 计数功能.否则对于 empty students
变量 selectedStudentsCount
将返回 0
.$scope.selectedStudentsCount = function() {无功计数 = 0;angular.forEach($scope.students, function(student){计数 += student.isSelected ?1:0;});返回计数;}
请注意 selectedStudentsCount
是一个函数,因此必须在模板中使用 ()
调用它,例如
所选学生总数:{{selectedStudentsCount()}}
I have an array of objects as follow.
$scope.students = [{'isSelected': true},
{'isSelected': true},
{'isSelected': false},
{'isSelected': true},
{'isSelected': true},
]
How can i get the count items that have isSelected
property set to true
?
UPDATE:
The problem is $scope.students
is fetched from a REST api and simply looping over the $scope.students variable does not work as the variable is undefined
until the request is completed, and so the loop code errors out saying $scope.students is not defined
.
I tried using $watch
but in that case i have to define the loop under the watch directive and it only works one time when $scope.students is defined, after that the loop does not work as $scope.students itself is not changing.
You can add the following method to your controller. Variable selectedStudentsCount
in your scope will keep number of all selected students (where isSelected
is set to true
).
Function counting selected users in angular.forEach
will be executed only if students
is not empty. Otherwise for empty students
variable selectedStudentsCount
will return 0
.
$scope.selectedStudentsCount = function() {
var count = 0;
angular.forEach($scope.students, function(student){
count += student.isSelected ? 1 : 0;
});
return count;
}
Please note that selectedStudentsCount
is a function so it will have to be called with ()
in your template e.g.
<h2>Total selected students: {{selectedStudentsCount()}}</h2>
这篇关于获取数组中具有某些属性的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!