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
755 views
in Technique[技术] by (71.8m points)

angularjs - Validating nested form in angular

Having this ordinary (name attribute is requred by server) form with angular and can't figured out how to make validations work. What should i put into ng-show="TODO"

http://jsfiddle.net/Xk3VB/7/

<div ng-app>
  <form ng-init="variants = [{duration:10, price:100}, {duration:30, price:200}]">
    <div ng-repeat="variant in variants" ng-form="variant_form">
      <div>
        <label>Duration:</label>
        <input name="variants[{{$index}}][duration]" ng-model="variant.duration" required />
        <span ng-show="TODO">Duration required</span>
      </div>
      <div>
        <label>Price:</label>
        <input name="variants[{{$index}}][price]" ng-model="variant.price" />
        <span ng-show="TODO">Price required</span>
      </div>
    </div>
  </form>
</div>

ps: this is just piece of form, which is more complicated

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

AngularJS relies on input names to expose validation errors.

Unfortunately, as of today it is not possible (without using a custom directive) to dynamically generate a name of an input. Indeed, checking input docs we can see that the name attribute accepts a string only.

Long story short you should rely on ng-form to validate dynamically created inputs. Something like :

<div ng-repeat="variant in variants" >
  <ng-form name="innerForm">
     <div>
        <label>Duration:</label>
        <input name="duration" ng-model="variant.duration" required />
        <span ng-show="innerForm.duration.$error.required">Duration required</span>
    </div>
    <div>
        <label>Price:</label>
        <input name="price" ng-model="variant.price" required/>
        <span  ng-show="innerForm.price.$error.required">Price required</span>
    </div>
  </ng-form>

Working fiddle here

UPDATE : Base on your serverside requirement why not do something like that :

<input type="hidden" name="variants[{{$index}}][duration]" ng-model="variant.duration"/>
<input name="duration" ng-model="variant.duration" required />

The hidden input will be the one read by the server while the other one will be used to do the client side validation (later discarded by server). It s kind of an hack but should work.

PS : Be sure that your form is valid before actually submitting it. Can be done with ng-submit


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

...