计算angularjs中已选中复选框的数量

时间:2014-06-27 11:52:02

标签: javascript angularjs

我尝试使用此代码显示已检查的复选框的数量

<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>

我也在{{}}内尝试了count()但不起作用。

demo plunker

3 个答案:

答案 0 :(得分:12)

您应按checked属性

过滤用户
<p>total checked: {{ (data | filter:{checked: true }).length }}</p>

答案 1 :(得分:3)

标记:

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

控制器:

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

working plunker

答案 2 :(得分:2)

您可以创建一个函数来计算控制器中所有已选中的元素:

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

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

      return count;
   };

然后在 HTML

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

ASSOCIATE PLUNKER