首页 文章

如何通过AngularJS有条件地要求表单输入?

提问于
浏览
226

假设我们正在使用AngularJS构建一个地址簿应用程序(人为的例子) .

我们有一个联系人表单,其中包含电子邮件和电话号码的输入,我们想要 one or the other ,但是 not both :如果 phone 输入为空或无效,我们只需要 email 输入,反之亦然 .

Angular有一个 required 指令,但从文档中不清楚如何在这种情况下使用它 . 那么我们如何才能有条件地要求表格领域呢?写一个自定义指令?

4 回答

  • 9

    有's no need to write a custom directive. Angular'的文档很好但不完整 . In fact,有一个名为 ngRequired 的指令,它接受一个Angular表达式 .

    <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/

  • 449

    如果你想要输入其他所需的输入:

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

    问候 .

  • 21

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

    <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中使用条件必需填充 .

  • 10

    对于Angular2

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

相关问题