数,用AngularJS打印选中的输入

Count & print the checked inputs with AngularJS

本文关键字:输入 打印 AngularJS      更新时间:2023-09-26

我使用ng-repeat打印输入复选框的列表。如何计算和打印已选中的复选框的数目?

JavaScript

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.lists = [{'id':'1', 'name':'list 1'},
                    {'id':'2', 'name':'list 2'},
          {'id':'3', 'name':'Macbook Pro'},
          {'id':'4', 'name':'Dell Optiplex 755'},
          {'id':'5', 'name':'Google Nexus S'}
          ];
});

HTML

<ul style="padding:10px;">
  <input type="text" ng-model="fil.name" />
  <li ng-repeat="list in lists | filter:fil">
    <div style="margin-bottom:0;" class="checkbox">
      <label>
        <input type="checkbox" name="list_id[]" value="{{list.id}}" />
           {{list.name}}
      </label>
    </div>
  </li>
</ul>

http://plnkr.co/edit/4swnCWen370VhTuca0u2?p =预览

JS:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.lists = [
    {'id':'1', 'name':'list 1', checked: true},
    {'id':'2', 'name':'list 2'},
    {'id':'3', 'name':'Macbook Pro'},
    {'id':'4', 'name':'Dell Optiplex 755'},
    {'id':'5', 'name':'Google Nexus S'}
  ];
  $scope.$watch('lists', function(lists){
    $scope.count = 0;
    angular.forEach(lists, function(list){
      if(list.checked){
        $scope.count += 1;
      }
    })
  }, true);
});

视图:

<body ng-controller="MainCtrl">
  <ul style="padding:10px;">
    <input type="text" ng-model="fil.name" />
    <li ng-repeat="list in lists | filter:fil">
      <div style="margin-bottom:0;" class="checkbox">
        <label>
          <input type="checkbox" name="list_id[]" ng-model="list.checked" value="{{list.id}}" />
             {{list.name}}
        </label>
      </div>
    </li>
  </ul>
  <strong>Count: {{count}}</strong>
</body>

Plnkr