get count of items with some property in an array

后端 未结 3 755
离开以前
离开以前 2020-11-29 11:19

I have an array of objects as follow.

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


        
相关标签:
3条回答
  • 2020-11-29 11:21

    You could also use javascript filter method (see 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;
    }
    
    0 讨论(0)
  • 2020-11-29 11:26

    There is another way to do this: the AngularJS filters. You can write this:

    var selectedCount = $filter('filter')($scope.students, { isSelected: true }).length;
    
    0 讨论(0)
  • 2020-11-29 11:41

    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 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; 
    }
    

    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>
    
    0 讨论(0)
提交回复
热议问题