2017-05-18 33 views
0

比方说,我有这样的疑问对象:Angularjs复选框组生效(动态选项)

$scope.question = { 
    id: 1, 
    question: 'q?', 
    required: true, 
    control: { 
     type: 'multiple_check', 
     options: [{ 
      value: '1st option' 
     }, ... ] 
    } 
} 

这种形式:

<form name="s.form" novalidate> 
    <h1>{{ question.question }}</h1> 
    <label ng-repeat="option in question.control.options"> 
     <input type=" name="xxx" 
      ng-model="question.answer[$index]" ng-required="question.required" /> 
     {{ option.value }} 
    </label> 
</form> 

而且我与验证现在卡住。我为此created a pen

{{s.form。$有效}}应该给我真正当形式是有效的,但只有在组中的所有复选框被选中

{{s.form ['XXX返回true ']。$ valid}}当至少有一个复选框被选中时,它应该是真实的,但只有当最后一个复选框被选中时才会真正返回true

我希望能够选择至少一个复选框更多)。当至少一个选中时,表单和组将是有效的。

我该如何做到这一点?已经尝试了很多东西,但不能使这个工作。

谢谢。

回答

0

您可以通过观看复选框为波纹管

$scope.$watch("question.control.options" , function(n,o){ 
    var trues = $filter("filter")(n , {value:true}); 
    $scope.flag = trues.length; 
}, true); 

注意让自己的验证:复选框的值必须是一个布尔值,所以改变你的问题的价值

$scope.question = { 
    id: 1, 
    question: 'q?', 
    required: true, 
    control: { 
     type: 'multiple_check', 
     options: [{ 
      value: false, 
      label: '1st option' 
     }, ... ] 
    } 
} 

和您的视图

<form name="s.form" novalidate> 
    <h1>{{ question.question }}</h1> 
    <label ng-repeat="option in question.control.options"> 
     <input type=" name="xxx" 
     ng-model="question.control.options.value" ng-required="question.required" /> 
     {{ option.label }} 
    </label> 
</form> 

这里是一个fiddle使这种方法

+0

还是同样的问题,没有什么改变。 http://jsfiddle.net/JBwmA/368/ –

0

这实际上很难,但我认为它现在可行。 Here's working demo

对于那些想知道我在我的应用中包含this module的人。

然后改变了HTML代码:

<form name="s.form" novalidate> 

    form valid? <b>{{ s.form.$valid | json }}</b> 

    <div ng-repeat="question in questions"> 
     <h1>{{ question.question }}</h1> 
     <label ng-repeat="option in question.control.options"> 
      <input type="checkbox" name="xxx_{{ question.id }}" 
      checklist-model="question.answer" checklist-value="option" ng-required="question.required && !question.answer.length" /> 
      {{ option.value }} 
     </label> 

     <p>question valid? {{ s.form['xxx_'+question.id].$valid | json }}</p> 
     answer: {{ question.answer }} 
    </div> 

</form>