获取具有数组中某些属性的项的计数 [英] get count of items with some property in an array

查看:183
本文介绍了获取具有数组中某些属性的项的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组如下。

I have an array of objects as follow.

$scope.students = [{'isSelected': true},
    {'isSelected': true},
    {'isSelected': false},
    {'isSelected': true},
    {'isSelected': true},
]

如何获得 isSelected的计数项目属性设置为 true

问题是 $ scope.students 是从REST api中获取的,只是循环遍历$ scope.students变量不起作用,因为变量是 undefined 直到请求完成,因此循环代码错误说明 $ scope.students未定义

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.

我尝试使用 $ watch 但是在这种情况下我必须在watch指令下定义循环,它只能运行一次当定义$ scope.students时,循环不起作用$ scope.students本身不会改变。

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.

推荐答案

您可以将以下方法添加到控制器中。您的范围中的变量 selectedStudentsCount 将保留所有所选学生的数量(其中 isSelected 已设置到 true )。

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).

angular.forEach 中的选定用户的功能仅在<$时执行c $ c>学生不为空。否则 学生变量 selectedStudentsCount 将返回 0

Function counting selected users in angular.forEach will be executed only if studentsis 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; 
}

请注意 selectedStudentsCount 是一个函数,因此必须在模板中使用()调用,例如

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆