7

仅当满足特定条件时,我才需要对表单字段应用验证。假设我有这样的表格:

<div ng-controller="MyController">
 <form name="myForm">
  <div>
   <div class="" ng-class="{error: myForm.gender.$invalid}">
    Gender:
   </div>
   Male   <input type="radio" name="gender" value="M" ng-model="survey.gender"   required/> 
   Female <input type="radio" name="gender" value="F" ng-model="survey.gender" required/> 
  </div>

  <div ng-show="survey.gender == 'F'">
   <div class="">
    Are you pregnant?
   </div>
   Yes <input type="radio" name="pregnant" value="Y" ng-model="survey.pregnant"/>
   No  <input type="radio" name="pregnant" value="N" ng-model="survey.pregnant"/>
  </div>
 </form>
</div>

我只想在用户选择女性时才提出怀孕问题。Angular 是否为此提供了任何类型的验证?

4

2 回答 2

16

好吧,实际上我刚刚找到了执行此操作的指令。我只需要添加ng-required="survey.gender == 'F'".

代码现在看起来像这样:

<div ng-controller="MyController">
 <form name="myForm">
  <div>
   <div class="" ng-class="{error: myForm.gender.$invalid}">
    Gender:
   </div>
   Male   <input type="radio" name="gender" value="M" ng-model="survey.gender" required/> 
   Female <input type="radio" name="gender" value="F" ng-model="survey.gender" required/> 
  </div>

  <div ng-show="survey.gender == 'F'">
   <div class="">
    Are you pregnant?
   </div>
   Yes <input type="radio" name="pregnant" value="Y" ng-model="survey.pregnant" ng-required="survey.gender == 'F'">
   No  <input type="radio" name="pregnant" value="N" ng-model="survey.pregnant" ng-required="survey.gender == 'F'">
  </div>
 </form>
</div>
于 2013-06-20T15:35:45.597 回答
3

是的,看看ng-required。文档不好,但是那个链接有一些。

这里还有一个与您在较早日期提出的问题相似的问题。

于 2013-06-20T15:40:59.677 回答