2

I try to display how many checked checkboxes using this code

<li class="list-group-item" ng-repeat="user in data">
  <input type="checkbox" ng-model="user.checked"/>
  {{user.name}}
</li>

<p>total checked: {{user.checked.length}}</p>

I also tried count() within the {{}} but doesn't work.

demo plunker

2
  • Try {{user.checked|length}} ? Commented Jun 27, 2014 at 11:53
  • @Fabien, That won't work Commented Jun 27, 2014 at 11:56

3 Answers 3

12

You should filter users by checked property:

<p>total checked: {{ (data | filter:{checked: true }).length }}</p>
Sign up to request clarification or add additional context in comments.

5 Comments

that's neat. working plunker: plnkr.co/edit/Vbp6KfXfqnhAp7KqYUAi?p=preview
that's smart :) +1 definitely
Thanks buddy .. I spent hours to find it ... excellent example.
Three years ago still valid for angular 1.5. A little note, the checkbox must have ng-model=user.checked (as it is in plunker) but the key is the attribute checked.
very neat, for ages I've been using ng-change and looping the data. This is much simpler.
3

Markup:

<p>total checked: {{checkedCount()}}</p>

Controller:

$scope.checkedCount = function(){
  return $scope.data.filter(function(person){
    return person.checked;
  }).length;
}

working plunker

4 Comments

as ryeballer alluded, Array.filter isn't supported in IE8. source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
nice code but I gt this in console Error: [$interpolate:interr] errors.angularjs.org/1.2.16/$interpolate/……pic&p1=TypeError%3A%20Cannot%20read%20property%20'filter'%20of%20undefined
@user3522729, are you using IE8?
Do you get that error when viewing the plunker? Or is this in your own code now?
2

You can create a function to calculate all the checked elements inside your controller:

    $scope.calculateChecked = function() {
      var count = 0;

      angular.forEach($scope.data, function(value) {
        if(value.checked)
          count++;
      });

      return count;
   };

and then in your HTML

 <p>total checked: {{calculateChecked()}}</p>

ASSOCIATE PLUNKER

1 Comment

yes we sure did, your solution is quite beautiful and readable but it won't work on some browser versions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.