Angular.js至少需要一个复选框

时间:2014-11-17 18:23:32

标签: javascript angularjs

如果这是重复的话我不会感到惊讶,但是我找不到任何简单的东西。

我只需要用户选择至少一个复选框,但我很困惑如何实现这一目标。

    <input type="checkbox" ng-model="myForm.first" /> First <br />
    <input type="checkbox" ng-model="myForm.second" />Second <br />
    <input type="checkbox" ng-model="myForm.third" /> Third

2 个答案:

答案 0 :(得分:6)

<input type="checkbox" ng-model="myForm.first" ng-required="myForm.first || myForm.second || myForm.third" /> First <br />
<input type="checkbox" ng-model="myForm.second" ng-required="myForm.first || myForm.second || myForm.third"/>Second <br />
<input type="checkbox" ng-model="myForm.third" ng-required="myForm.first || myForm.second || myForm.third"/> Third

答案 1 :(得分:0)

HTML

<div ng-app="myApp" ng-controller="myCrtl as myForm">
    <input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.first" ng-change="myForm.onCheckBoxSelected()" /> First <br />
    <input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.second"  ng-change="myForm.onCheckBoxSelected()"/>Second <br />
    <input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.third"  ng-change="myForm.onCheckBoxSelected()"/> Third<br/>
    <span style="color:red;" ng-if="!myForm.selectedOptions ">Required</span>
</div>    

JS

angular.module('myApp',[])
    .controller('myCrtl',function(){
        var myForm=this;
        myForm.onCheckBoxSelected=function(){

        var flag=false;
        for(var key in myForm.selectedOptions){

            if(myForm.selectedOptions[key]){
                flag=true;
            }
        }
        if(!flag){
            myForm.selectedOptions = undefined;
        }
   };

 });

JS小提琴:http://jsfiddle.net/fodyyskr/