我怎么能有条件地要求与AngularJS形式投入?(How can I conditionally

2019-06-21 05:32发布

假设我们正在构建与AngularJS地址簿应用程序(人为的例子)。

我们有接触的形式,对电子邮件和电话号码输入,我们希望能够要求一个或另一个 ,但不能同时 :我们只希望email被要求输入,如果phone输入是空的或无效的,反之亦然。

角有一个required指令,但它不是从文档清楚如何在这种情况下使用它。 那么,如何才能有条件地需要一个表单字段? 编写自定义指令?

Answer 1:

有没有必要写一个自定义的指令。 角的文档是好的,但不完整。 事实上 ,有一种叫指令ngRequired ,接受一个角度表达。

<input type='email'
       name='email'
       ng-model='contact.email' 
       placeholder='your@email.com'
       ng-required='!contact.phone' />

<input type='text'
       ng-model='contact.phone'             
       placeholder='(xxx) xxx-xxxx'
       ng-required='!contact.email' />  

下面是一个更完整的例子: http://jsfiddle.net/uptnx/1/



Answer 2:

如果你想,如果把其他被写入需要输入:

   <input type='text'
   name='name'
   ng-model='person.name'/>

   <input type='text'
   ng-model='person.lastname'             
   ng-required='person.name' />  

问候。



Answer 3:

简单,你可以使用角度验证,如:

 <input type='text'
   name='name'
   ng-model='person.name'
   ng-required='!person.lastname'/>

   <input type='text'
   name='lastname'
   ng-model='person.lastname'             
   ng-required='!person.name' /> 

现在,您可以只在一个文本字段中填入值。 要么你可以填写名字或姓氏。 通过这种方式,你可以在AngularJs使用条件所需的填充。



Answer 4:

对于Angular2

<input type='email' 
    [(ngModel)]='contact.email'
    [required]='!contact.phone' >


文章来源: How can I conditionally require form inputs with AngularJS?