【发布时间】:2015-06-27 09:57:12
【问题描述】:
我正在努力实现两件事:
将数组绑定到复选框列表(只是一个字符串数组),并且
将用户可以选择的数量限制为介于 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