如何使用Angular.js/Javascript限制单击的复选框
我需要一个帮助。我在循环中有很多复选框,我需要使用Angular.js限制那些使用某些条件的复选框。让我先解释一下我的代码。我的代码存在。我可以每天在那里检查一个复选框,如果用户单击如何使用Angular.js/Javascript限制单击的复选框,javascript,html,angularjs,Javascript,Html,Angularjs,我需要一个帮助。我在循环中有很多复选框,我需要使用Angular.js限制那些使用某些条件的复选框。让我先解释一下我的代码。我的代码存在。我可以每天在那里检查一个复选框,如果用户单击+按钮,复选框将增加,这里我需要当用户从任何一天起选中max2复选框时,另一天将被禁用。从7天起,整个表中只能选中2个复选框。我还需要在单击store按钮后,两个复选框值以及相应的行下拉数据应进入控制器端函数。请检查我的代码并帮助我。因此,另一个答案会让您走上正确的轨道,而这个答案会让您一直走到正确的轨道。基本上,您
+
按钮,复选框将增加,这里我需要当用户从任何一天起选中max2
复选框时,另一天将被禁用。从7
天起,整个表中只能选中2个复选框。我还需要在单击store
按钮后,两个复选框值以及相应的行下拉数据应进入控制器端函数。请检查我的代码并帮助我。因此,另一个答案会让您走上正确的轨道,而这个答案会让您一直走到正确的轨道。基本上,您希望利用angular的ng disabled
属性,当您给它的表达式的计算结果为true
时,它附加到的表单字段将被禁用
在html中,当满足条件时,您可以将以下内容放在希望禁用的任何表单字段上:
ng-disabled="isDisabled($parent.$index, $index)"
父索引将引用当前外部循环的日期,而索引则引用内部循环中的当前答案
我用于实现此解决方案的主控制器逻辑如下:
// initialize an array of selections
$scope.selectedAnswers = [];
// check if answer is selected...
// have to keep track of both the index of the answer and its parent day
$scope.answerIsSelected = function(dayIdx, answerIdx) {
var thisAnswer = $scope.days[dayIdx].answers[answerIdx];
return $scope.selectedAnswers.indexOf(thisAnswer) > -1;
};
// depending on whether answer is already selected,
// adds it to or splices it from the selectedAnswers array
$scope.toggleAnswerSelected = function(dayIdx, answerIdx) {
var thisAnswer = $scope.days[dayIdx].answers[answerIdx];
if ($scope.answerIsSelected(dayIdx, answerIdx)) {
$scope.selectedAnswers.splice($scope.selectedAnswers.indexOf(thisAnswer), 1);
} else {
$scope.selectedAnswers.push(thisAnswer);
}
};
// the check on each form element to see if should be disabled
// returns true if the answer is not an element in the selected array
// and if there are already two answers in the array
$scope.isDisabled = function(dayIdx, answerIdx) {
return !$scope.answerIsSelected(dayIdx, answerIdx) && $scope.selectedAnswers.length === 2;
};
最后,在行末尾的复选框上显示所需的属性:
<input type="checkbox"
name="chk"
value="true"
ng-checked="answerIsSelected($parent.$index, $index)"
ng-click="toggleAnswerSelected($parent.$index, $index)"
ng-disabled="isDisabled($parent.$index, $index)">
安古拉斯普朗克
文件。写(“”);
普朗克
白天
类别
子类别
评论或特别促销
添加更多
{{d.day_name}
选择类别
选择子类别
{{sendToServer}json}
将每个复选框的值绑定到一个模型(使用ng model
指令),并使用$scope.$watch
功能监控选中复选框的数量,并根据该数量启用或禁用所需元素。您可以在那里编辑您的答案吗。在plunkr中,我检查了您的答案,我只需要禁用复选框而不是其他字段,还需要使用相应的行all值检索选中的值。只需从所有其他输入/选择中删除ng disabled
属性,即可禁用复选框,但我返回并相应地编辑了它们。当您单击Store
时,pre
显示每个选定答案行的选定值。这不能回答你的问题吗?是的,我只需要在勾选2后禁用复选框。编辑后请发表评论。对不起,伙计们,这将从“问题”变成“免费做我的作业”,删除我的答案并投票决定立即关闭此项。@BennettAdams:您的代码工作正常,非常灵活。谢谢。