get count of items with some property in an array

angularjs, javascript

Solution

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>

Problem

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.

Original source