Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

Dynamic validation and name in a form with AngularJS

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...