Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count selected checkboxes in Angular?

I need to count the number of items I have selected in a 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 to @Stewie I got it working.

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 checkbox

<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;
        }
    };
like image 229
Steven Avatar asked Dec 31 '13 09:12

Steven


1 Answers

Your use of ngRepeat looks wrong. It should be "item in items" not the other way around. Also, you're not using ng-model on your inputs, which makes it much harder to get the count.

So, if you add ng-model you can get the count in many 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>
like image 57
Stewie Avatar answered Oct 05 '22 00:10

Stewie