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

时间:2015-04-20 15:18:29

标签: javascript arrays angularjs checkbox

我正在努力实现两件事:

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

  2. 将用户可以选择的数量限制为两者之间的数字 1,可用项目数量少于1。

  3. 我可以让(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);
            }
          }      
        }
      };
    
    });
    

1 个答案:

答案 0 :(得分:2)

我喜欢plunker而不是codepen。所以我创建了这个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}}