我怎么能有条件地要求与AngularJS表单输入?

我怎么能有条件地要求与AngularJS表单输入?

问题描述:

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

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

有没有必要写一个自定义的指令。棱角分明的文档是好的,但不完整。 事实上,有一个叫指令 ngRequired ,这需要一个角前pression。

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/