如何计算Angular中的选定复选框?

时间:2013-12-31 09:42:36

标签: javascript html5 angularjs

我需要计算我在列表中选择的项目数。

我有以下列表:

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

有类似var count = $scope.item.selected.count的内容吗?

更新
感谢@Stewie,我得到了它。

我最终使用了这段代码:

    // 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}})

如果您还有select all复选框

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

然后代码将是:

    $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;
        }
    };

1 个答案:

答案 0 :(得分:3)

您对ngRepeat的使用看起来不对。它应该是“项目中的项目”,而不是相反。 此外,您没有在输入上使用ng-model,这使得计算更加困难。

因此,如果添加ng-model,您可以通过多种方式获取计数,其中一种方式是:

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>