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
?
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.
You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.
The length property sets or returns the number of elements in an array.
To count the duplicates in an array:Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .
There is another way to do this: the AngularJS filters. You can write this:
var selectedCount = $filter('filter')($scope.students, { isSelected: true }).length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With