例如
<input type="checkbox" ng-repeat="color in colors"
ng-class="checked <= 3 ? '' : 'disabled'"/>
当我选择最多三个复选框时,我想禁用其余复选框。这样做的角度方式是什么?我是否能够保留所有内容&#34;内联&#34;或者我是否必须使用过滤器/模型?
答案 0 :(得分:2)
实现此目的的一种方法是将ng-model分配给您的复选框,
并在控制器上有功能来确定单击它们的数量,以及是否禁用其余部分:
app.controller('MainCtrl', function($scope) {
$scope.colors = ['red', 'blue', 'purple', 'yellow'];
$scope.selected = [];
$scope.check = function(color) {
var pos = $scope.selected.indexOf(color);
if (pos > -1) {
$scope.selected.splice(pos,1);
} else {
$scope.selected.push(color);
}
}
$scope.disable = function(color) {
return $scope.selected.length >= 3 && $scope.selected.indexOf(color) == -1;
}
});
HTML:
<body ng-app ng-controller="MainCtrl">
<input type="checkbox" ng-repeat="color in colors" ng-model="test" ng-change="check(color)" ng-disabled="disable(color)">
</body>
答案 1 :(得分:1)
我会将一些函数绑定到作用域,因为你所做的事情相当复杂(取决于数据的结构。
检查出来:
http://plnkr.co/edit/cfNGnx5eNXTuirCduWaG?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = [
{id: 'a', checked: false},
{id: 'b', checked: false},
{id: 'c', checked: true},
{id: 'd', checked: true},
{id: 'e', checked: false}
];
$scope.selected = function() {
var i, selectedCount = 0;
for (i = 0; i < $scope.data.length; i++) {
if ($scope.data[i].checked) {
selectedCount += 1;
}
}
return selectedCount;
};
});
模板:
<body ng-app="plunker" ng-controller="MainCtrl">
<p>{{data | json}}</p>
<p>Greater than 3? <span ng-bind="selected()"></span>
</p>
<label ng-repeat="elem in data">{{elem.id}}
<input ng-disabled="selected() > 2 && !elem.checked" ng-model="elem.checked" type="checkbox" ng-checked="elem.checked">
</label>
</body>
答案 2 :(得分:1)
我认为这就是你要找的东西:
var app = angular.module('app', []);
app.directive('checkboxes', function() {
return {
restrict: 'A',
scope: {
colors: '=checkboxes'
},
template: '<div ng-repeat="color in colors"><input type="checkbox" ng-disabled="count()>=3 && !color.checked" ng-model="color.checked" /> <span ng-class="{disabled:count()>=3 && !color.checked}">{{color.name}}</span></div>',
controller: function($scope, $element) {
function countChecked(arr, fn) {
var checkCount = 0;
for (var i = 0; i < arr.length; ++i) {
if (fn(arr[i]) === true) {
++checkCount;
}
}
return checkCount;
}
$scope.count = function() {
return countChecked($scope.colors, function(color) {
return color.checked;
});
}
}
}
});
app.controller('ctrl', function($scope) {
$scope.colors = [{
name: 'red'
}, {
name: 'green'
}, {
name: 'blue'
}, {
name: 'orange'
}, {
name: 'black'
}];
});
&#13;
.disabled {
color: grey;
font-style: italic;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="ctrl">
<div checkboxes="colors">
</div>
Colors: {{colors}}
<br />
</body>
&#13;