javascript 如何要求至少 1 个复选框用于 AngularJS 表单验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33181624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to require at least 1 checkbox for AngularJS Form Validation?
提问by Actively
I have an array of JSON objects which is displayed in a form. I would like to have the form validation work where a user has to select at least one checkbox for the entire form to be valid.
我有一个以表格形式显示的 JSON 对象数组。我想让表单验证工作,用户必须至少选择一个复选框才能使整个表单有效。
I know that the ng-required
can be used but with the implementation I have, it means that all of them have to be selected for it to be valid.
我知道ng-required
可以使用,但是对于我的实现,这意味着必须选择所有这些才能使其有效。
Here is the code I have so far:
这是我到目前为止的代码:
index.html:
索引.html:
<div ng-repeat="item in volunteerOptions">
<label class="checkbox"><input type="checkbox" value="" data-ng-model="item.selected" ng-required="true">{{ item.content }}</label>
</div>
<button type="submit" class="btn btn-success" ng-disabled="!memberRegistrationForm.$valid">Submit</button>
controller.js
控制器.js
$scope.volunteerOptions = [
{ content : 'Content 1', selected : false },
{ content : 'Content 2', selected : false },
{ content : 'Content 3', selected : false },
{ content : 'Content 4', selected : false },
];
Any ideas on how I would be able to achieve this behaviour?
关于我如何能够实现这种行为的任何想法?
回答by Joseph
You can add another scope property and use array.some
to check if any of the selected
are true
. Then feed that scope property to ng-required
. Something like
您可以添加另一个范围属性并用于array.some
检查是否有任何selected
are true
。然后将该范围属性提供给ng-required
. 就像是
$scope.isOptionsRequired = function(){
return !$scope.volunteerOptions.some(function(options){
return options.selected;
});
}
<input type="checkbox" value="" data-ng-model="item.selected" ng-required="isOptionsRequired()">