使用复选框和AngularJS需要 [英] Using checkboxes and required with AngularJS

查看:117
本文介绍了使用复选框和AngularJS需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试使用HTML5 要求属性为我的组复选框,但我不觉得有NG-形式来实现它的好方法。

I've tried to use the html5 required attribute for my group of checkboxes but I don't find a nice way to implement it with ng-form.

当一个复选框被选中我想要输入元素的值被推向值的阵列

When a checkbox is checked I want the value of that input-element to be pushed to an array of values.

角必需的验证似乎看与输入元素相关联的NG-模式,但我怎么能几个复选框链接到相同型号和更新它与输入字段的值?

The angular required validator seems to watch the ng-model associated with the input element, but how can I link several checkboxes to the same model and update it's value with the value of the input field?

现在实现是像这个小提琴

<div ng-controller="myCtrl">
  <ng-form name="myForm">
    <span ng-repeat="choice in choices">
      <label class="checkbox" for="{{choice.id}}">
        <input type="checkbox" required="required" value="{{choice.id}}" ng-click="updateQuestionValue(choice)" ng-model="choice.checked" name="group-one" id="{{choice.id}}" />
        {{choice.label}}
      </label>
    </span>
    <input type="submit" value="Send" ng-click="submitSurvey(survey)" ng-disabled="myForm.$invalid" />
  </ng-form>
</div>​

该updateQuestionValue功能处理添加或值的数组卸下但每个复选框都有它自己的模式,这就是为什么每个复选框需求,以检查的形式是有效的。

The updateQuestionValue-function handles the adding or removing from the array of values but each checkbox has it's own model and that is why each checkbox needs to be checked in order for the form to be valid.

我知道了在一组单选按钮的工作,但他们在同一个模型作为一切工作只有一个可以被选中。

I've got it to work on a group of radio buttons, but they all work on the same model as only one can be selected.

推荐答案

如果你想,如果没有选择的选择,最简单的方法是检查在NG-disabled属性数组的长度,而无需设置提交按钮被禁用必需的属性。

If you want the submit button disabled if no choice is selected the easiest way is to check the length of the array in the ng-disabled attribute, without setting the required attribute

<input type="submit" value="Send" ng-click="submitSurvey(survey)" 
 ng-disabled="value.length==0" />

在这里看到更新的小提琴

另一种方式做,这将是检查数组长度的复选框的NG要求的属性。

Another way to do this would be to check the array length in the ng-required attribute of the checkboxes

<input type="checkbox" value="{{choice.id}}" ng-click="updateQuestionValue(choice)"
  ng-model="choice.checked" name="group-one" id="{{choice.id}}" 
  ng-required="value.length==0" />

第二小提琴

这篇关于使用复选框和AngularJS需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆