获取具有数组中某些属性的项的计数

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)

  • +1并且如果您负担得起ES6,您可能想使用像酷孩子一样的箭头功能'返回$ scope.students.filter((obj)=> obj.isSelected).length;` (2认同)

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)