【问题标题】:Limit checkbox selections and bind to an array in AngularJS限制复选框选择并绑定到AngularJS中的数组
【发布时间】:2015-06-27 09:57:12
【问题描述】:

我正在努力实现两件事:

  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 无法正常工作。我选择了所有 4 个,最终数据数组仅显示 1 个项目。
  • 这是所期望的行为 - 它将选定的数组限制为 1 个项目,由 var maxItems = 1 定义
  • 我明白了。因此,您正在研究如何将选择与最终数据数组同步。

标签: javascript arrays angularjs checkbox


【解决方案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}} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 2019-04-26
    • 2017-07-20
    • 2016-05-14
    • 2014-09-18
    • 2017-04-09
    • 1970-01-01
    相关资源
    最近更新 更多