我在angularJS上有ng-repeat复选框。我正在使用库checkboxlist来实现带有ng-repeat的多个复选框。我要求用户只能点击最大数量的复选框。我使用$ event.stopPropagation,它可以工作,但ng-model没有更新,因为我不知道如何访问checkboxlist。
控制器
$scope.mealCBChanged = function($event, mc){
if(mc.selectedCBId.length > 2){
$event.preventDefault();
alert("You can't select more than " + 2);
}
}
HTML
<div ng-repeat="mc in mealC">
<div ng-repeat="m in mc.meals">
<input type="checkbox" name="{{ m.id }}"
id="{{ m.name }}"
checklist-model="mc.selectedCBId"
ng-init="mc.selectedCBId = []"
ng-click="mealCBChanged($event, mc)"
checklist-value="m.name"/>
<label for="{{ m.name }}"><span class="checkbox primary primary"><span></span></span>{{ m.name }}</label>
</div>
</div>
问题
当我选择第三个复选框时,调用的警报和第三个复选框没有单击,因为$ event.preventDefault()工作正常。但是mc.selectedCBId在数组中有3个项目,据说它有两个项目。
答案 0 :(得分:0)
将输入绑定到数组以外的变量,例如:another_variable 在你的HTML中: 清单模型= “another_variable”
在您的代码中:
if(mc.selectedCBId.length == 2){
mc.selectedCBId = another_variable;
}
if(mc.selectedCBId.length == 2){
$event.preventDefault();
mc.selectedCBId = another_variable;
}
if(mc.selectedCBId.length > 2){
alert("You can't select more than 2" );
}
答案 1 :(得分:0)
从纯粹的Angular角度来看 - 不依赖于checkboxlist,你可以尝试这样的事情:
编辑:我添加了嵌套的ngRepeats并将checkCount的范围移动到每个mealC节点,以便OP可以看到如何使用纯角度而不是依赖第三方库使嵌套数据与复选框一起使用。第三方库有时很棒,但有时它们会增加比简单需求更多的开销。
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.mealC = [
{
checkCount: 0,
meals: [{ id: 1, name: "foo" }, { id: 2, name: "bar" }, { id: 3, name: "baz" }]
}, {
checkCount: 0,
meals: [{ id: 11, name: "gravy" }, { id: 12, name: "cake" }, { id: 13, name: "beer" }]
}
];
$scope.clicked = function(state, meal) {
!!state ? meal.checkCount++ : meal.checkCount--;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-repeat="mc in mealC">
<p>
There are currently {{mc.checkCount}} selected checkboxes in this section!
<div ng-repeat="m in mc.meals">
<input type="checkbox" id="{{ m.id }}" name="{{ m.name }}" ng-model="m.checked" ng-value="m.name" ng-change="clicked(m.checked, mc)" ng-disabled="mc.checkCount >= 2 && !m.checked" />
<label for="{{ m.name }}"><span class="checkbox primary primary"><span></span></span>{{ m.name }}</label>
</div>
</p>
</div>
</div>
</body>