get count of items with some property in an array

后端 未结 3 756
离开以前
离开以前 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: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.

    Total selected students: {{selectedStudentsCount()}}

提交回复
热议问题