AngularJS 表单中的动态验证和名称 [英] Dynamic validation and name in a form with AngularJS

查看:22
本文介绍了AngularJS 表单中的动态验证和名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个表格:http://jsfiddle.net/dfJeN/

如您所见,输入的名称值是静态设置的:

name="用户名"

,表单验证工作正常(添加一些内容并从输入中删除所有文本,必须出现文本).

然后我尝试动态设置名称值:http://jsfiddle.net/jNWB8/

name="{input.name}"

然后我将其应用于我的验证

login.{{input.name}}.$error.required

(此模式将用于 ng-repeat)但我的表单验证已损坏.它在我的浏览器中被正确解释(如果我检查我看到的元素 login.username.$error.required).

有什么想法吗?

在控制台中记录范围后,

{{input.name}}

表达式不是内插的.我的表单作为 {{input.name}} 属性但没有用户名.

更新:自 1.3.0-rc.3 name="{{input.name}}" 正常工作.请参阅 #1404

解决方案

你不能那样做.

假设你想要做的是你需要动态地向表单添加元素,比如 ng-repeat,你需要使用嵌套的 ng-form 以允许验证这些单个项目:

<div ng-repeat="项目中的项目"><ng-form name="innerForm"><input type="text" name="foo" ng-model="item.foo"/><span ng-show="innerForm.foo.$error.required">必需</span></ng-form>

<input type="submit" ng-disabled="outerForm.$invalid"/></表单>

遗憾的是,这并不是 Angular 的一个有据可查的特性.

I have this form : http://jsfiddle.net/dfJeN/

As you can see the name value for the input is statically set :

name="username"

, the form validation works fine (add something and remove all text from the input, a text must appears).

Then I try to dynamically set the name value : http://jsfiddle.net/jNWB8/

name="{input.name}"

Then I apply this to my validation

login.{{input.name}}.$error.required

(this pattern will be used in an ng-repeat) but my form validation is broken. It is correctly interpreted in my browser (if I inspect the element I saw login.username.$error.required).

Any Idea ?

EDIT: After logging the scope in the console it appears that the

{{input.name}}

expression is not interpolate. My form as an {{input.name}} attribute but no username.

UPDATE: Since 1.3.0-rc.3 name="{{input.name}}" works as expected. Please see #1404

解决方案

You can't do what you're trying to do that way.

Assuming what you're trying to do is you need to dynamically add elements to a form, with something like an ng-repeat, you need to use nested ng-form to allow validation of those individual items:

<form name="outerForm">
<div ng-repeat="item in items">
   <ng-form name="innerForm">
      <input type="text" name="foo" ng-model="item.foo" />
      <span ng-show="innerForm.foo.$error.required">required</span>
   </ng-form>
</div>
<input type="submit" ng-disabled="outerForm.$invalid" />
</form>

Sadly, it's just not a well-documented feature of Angular.

这篇关于AngularJS 表单中的动态验证和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆