如何使用 AngularJS 有条件地要求表单输入? [英] How can I conditionally require form inputs with AngularJS?
问题描述
假设我们正在使用 AngularJS 构建一个地址簿应用程序(人为的示例).
Suppose we're building an address book application (contrived example) with AngularJS.
我们有一个联系人表单,其中包含电子邮件和电话号码的输入,我们希望需要一个或另一个,但不是两者:我们只需要如果 phone
输入为空或无效,则需要 email
输入,反之亦然.
We have a form for contacts that has inputs for email and phone number, and we want to require one or the other, but not both: We only want the email
input to be required if the phone
input is empty or invalid, and vice versa.
Angular 有一个 required
指令,但文档中并不清楚在这种情况下如何使用它.那么我们如何有条件地要求一个表单域呢?编写自定义指令?
Angular has a required
directive, but it's not clear from the documentation how to use it in this case. So how can we conditionally require a form field? Write a custom directive?
推荐答案
无需编写自定义指令.Angular 的文档很好,但并不完整.其实,有一个指令叫做ngRequired
,这需要一个 Angular 表达式.
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' />
这里有一个更完整的例子:http://jsfiddle.net/uptnx/1/
Here's a more complete example: http://jsfiddle.net/uptnx/1/
这篇关于如何使用 AngularJS 有条件地要求表单输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!