[英]Limit checkbox selections and bind to an array in AngularJS
我正在努力實現兩件事:
將數組綁定到復選框列表(只是一個字符串數組),然后
將用戶可以進行的選擇數量限制為1到可用項目的數量之間的乘以1。
我可以使(2)起作用,直到用戶單擊最后一個項目,這時它會失去跟蹤,並且這些項目仍保持選中狀態。
交互式代碼在這里: http : //codepen.io/adamcodegarden/pen/bdbQqe (從類似的示例中派生)
我的HTML /角度代碼:
<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更喜歡節油器。 所以我創造了這個矮人
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}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.