How can I conditionally require form inputs with AngularJS?

后端 未结 5 953
一生所求
一生所求 2020-11-27 10:08

Suppose we\'re building an address book application (contrived example) with AngularJS.

We have a form for contacts that has inputs for email and phone number, and w

相关标签:
5条回答
  • 2020-11-27 10:31

    In AngularJS (version 1.x), there is a build-in directive ngRequired

    <input type='email'
           name='email'
           ng-model='user.email' 
           placeholder='your@email.com'
           ng-required='!user.phone' />
    
    <input type='text'
           ng-model='user.phone'             
           placeholder='(xxx) xxx-xxxx'
           ng-required='!user.email' /> 
    

    In Angular2 or above

    <input type='email'
           name='email'
           [(ngModel)]='user.email' 
           placeholder='your@email.com'
           [required]='!user.phone' />
    
    <input type='text'
           [(ngModel)]='user.phone'             
           placeholder='(xxx) xxx-xxxx'
           [required]='!user.email' /> 
    
    0 讨论(0)
  • 2020-11-27 10:41

    if you want put a input required if other is written:

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

    Regards.

    0 讨论(0)
  • 2020-11-27 10:46

    Simple you can use angular validation like :

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

    You can now fill the value in only one text field. Either you can fill name or lastname. In this way you can use conditional required fill in AngularJs.

    0 讨论(0)
  • 2020-11-27 10:47

    There's no need to write a custom directive. Angular's documentation is good but not complete. In fact, there is a directive called ngRequired, that takes an Angular expression.

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

    Here's a more complete example: http://jsfiddle.net/uptnx/1/

    0 讨论(0)
  • 2020-11-27 10:52

    For Angular2

    <input type='email' 
        [(ngModel)]='contact.email'
        [required]='!contact.phone' >
    
    0 讨论(0)
提交回复
热议问题