I have an array of objects as follow.
$scope.students = [{\'isSelected\': true},
{\'isSelected\': true},
{\'isSelected\': false},
{\'isSelected\':
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;
}
There is another way to do this: the AngularJS filters. You can write this:
var selectedCount = $filter('filter')($scope.students, { isSelected: true }).length;
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>