在验证嵌套角形式 [英] Validating nested form in angular

查看:132
本文介绍了在验证嵌套角形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了这个普通的形式角(name属性是由服务器requred),并不能想出如何使验证工作。我应该怎么投入NG秀=TODO

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:这仅仅是片的形式,这是更复杂的

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

感谢

推荐答案

AngularJS依靠输入名称揭露验证错误。

AngularJS relies on input names to expose validation errors.

不幸的是,今天的是不可能的(不使用自定义指令)动态生成的输入的一个名称。事实上,检查输入文档我们可以看到name属性只接受一个字符串。

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.

您应该依靠 NG-表长话短说,以验证动态创建输入。是这样的:

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>

工作拨弄这里

更新:基于您的服务器端的要求为什么不去做这样的事情:

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:请确保您的形式实际上是在提交前有效。可以用做NG提交

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

这篇关于在验证嵌套角形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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