限制复选框选择并绑定到 AngularJS 中的数组

Limit checkbox selections and bind to an array in AngularJS

我正在努力实现两件事:

  1. 将数组绑定到复选框列表(只是一个字符串数组),并且

  2. 将用户可以进行的选择数量限制在介于 1 和可用项目数减去 1。

我可以让 (2) 工作,直到用户单击最后一个项目,此时它失去跟踪并且项目保持选中状态。

交互式代码在此处:http://codepen.io/adamcodegarden/pen/bdbQqe(从类似示例中分叉)

我的HTML/Angular代码:

<p ng-repeat="item in allOptions" class="item" id="{{item}}">
      {{item}} <input type="checkbox" ng-change="sync(bool, item)" ng-model="bool" ng-checked="isChecked(item)"> Click this to sync this item with the target array.  {{item}} Selected: {{bool}}

和 JS:

var myApp = angular.module("myApp", []);

var maxItems = 1;

myApp.controller('myController', function($scope) {

  $scope.isChecked = function(item){
      var match = false;
      for(var i=0 ; i < $scope.data.length; i++) {
        if($scope.data[i] === item) {
          match = true;
        }
      }
      return match;
  };

  $scope.allOptions = [
    'one', 'two', 'three', 'four'
  ];

  $scope.data = [
  ];

  $scope.sync = function(bool, item){
    if (bool) {
      // add item
      $scope.data.push(item);
      // if we have gone over maxItems:
      if ($scope.data.length > maxItems) {
        //remove oldest item
        $scope.data.splice(0,1);
      }
    } else {
      // remove item
      for (var i=0 ; i < $scope.data.length; i++) {
        if ($scope.data[i] === item){
          $scope.data.splice(i,1);
        }
      }      
    }
  };

});

比起 codepen,我更喜欢 plunker。所以我创建了这个 plunker

http://plnkr.co/edit/l8gxQHXBQdFeKIuwf3f0?p=preview

主要思想是我将原始数组格式化为:

$scope.allOptions = [
   {key: 'one'}, {key: 'two'}, {key: 'three'}, {key:'four'}
];

同步逻辑也有细微变化:

$scope.sync = function(bool, item){
if (bool) {
  // add item
  $scope.data.push(item);
  // if we have gone over maxItems:
  if ($scope.data.length > maxItems) {
    //remove first item
    $scope.data[0].checked = false;
    $scope.data.splice(0,1);
  }
} else {
  // remove item
  for (var i=0 ; i < $scope.data.length; i++) {
    if ($scope.data[i] === item) {
      $scope.data.splice(i,1);
    }
  }      
}

};

同时更改 html 部分:

<p ng-repeat="item in allOptions" class="item" id="{{item.key}}">
  {{item.key}} <input type="checkbox" ng-change="sync(item.checked, item)"    ng-model="item.checked"> Click this to sync this item with the target array.  {{item.key}} Selected: {{bool}}