How to count selected checkboxes in Angular?

I need to count the number of items that I have selected in the list.

I have the following list:

<ul> <li ng-repeat="items in item"> <input type="checkbox" name="item_id[]" /> </li> </ul> 

Is there something like var count = $scope.item.selected.count ?

Update
Thanks @Stewie I got the job.

I ended up using this code:

  // Count the number of selected items $scope.selectedCounter = 0; $scope.change = function (item) { if (item.selected) { $scope.selectedCounter++ } else { $scope.selectedCounter-- } }; // HTML <ul> <li ng-repeat="item in items"> <input type="checkbox" ng-model="item.selected" ng-change="change(item)" /> </li> ... </ul> <span>Count: </span> ({{selectedCounter}}) 

If you also have a select all flag

 <input type="checkbox" ng-model="selected" class="checkAll" ng-change="selectAll(selected)" /> 

Then the code will be:

  $scope.selectAll = function (selected) { var items = $scope.items; angular.forEach(items, function (item) { item.selected = selected; }); // Update the counter if(selected){ $scope.selectedCounter = items.length; } else { $scope.selectedCounter = 0; } }; 
+8
javascript angularjs html5
source share
1 answer

Using ngRepeat does not look right. It should be "item in items", and not vice versa. In addition, you do not use ng-model on your inputs, which makes it difficult to get an account.

So, if you add an ng model, you can get the score in different ways, one of which is:

 app.controller('AppController', [ '$scope', function($scope) { $scope.items = [ {id: 1, title: "Can't Hold Us"}, {id: 2, title: "Just Give Me A Reason"}, {id: 3, title: "Mirrors"}, {id: 4, title: "Get Lucky"}, ]; $scope.selectedItems = 0; $scope.$watch('items', function(items){ var selectedItems = 0; angular.forEach(items, function(item){ selectedItems += item.selected ? 1 : 0; }) $scope.selectedItems = selectedItems; }, true); } ] ); 
 <body ng-controller="AppController"> <ul> <li ng-repeat="item in items"> <label> <input type="checkbox" name="payment_id[]" ng-model="item.selected" /> {{item.title}} </label> </li> </ul> <div>Selected Items Length: {{selectedItems}}</div> </body> 
+3
source share

All Articles