如何验证输入动态使用NG-重复创建,NG-展(角) [英] How to validate inputs dynamically created using ng-repeat, ng-show (angular)
问题描述
我有一个使用NG-reapeat创建的表。我想验证添加到表中的每个元件。的问题是,每个输入信元具有相同的名称作为细胞上面和下面。我试图使用 {{$}指数}
值来命名的投入,但尽管在HTML中出现的正确的字符串,它现在的工作。
I have a table that is created using ng-reapeat. I want to add validation to each element in the table. The problem is that each input cell has the same name as the cell above and below it. I attempted to use the {{$index}}
value to name the inputs, but despite the string literals in HTML appearing correct, it is now working.
下面是我的code截至目前:
Here is my code as of now:
<td>
<input ng-model="r.QTY" class="span1" name="QTY{{$index}}" ng-pattern="/^[\d]*\.?[\d]*$/" required/>
<span class="alert-error" ng-show="form.QTY{{$index}}.$error.pattern"><strong>Requires a number.</strong></span>
<span class="alert-error" ng-show="form.QTY{{$index}}.$error.required"><strong>*Required</strong></span>
</td>
我曾尝试删除`{{}}'从index,但这并不能工作。截至目前,对输入的验证属性工作正常,但不显示错误消息。
I have tried removing the `{{}}' from index, but that does not work either. As of now, the validation property of the input is working correctly, but the error message is not displayed.
任何人有什么建议吗?
编辑:除了下面伟大的答案,这里是一个博客文章,涵盖详细此问题:<一href=\"http://www.thebhwgroup.com/blog/2014/08/angularjs-html-form-design-part-2/\">http://www.thebhwgroup.com/blog/2014/08/angularjs-html-form-design-part-2/
In addition to the great answers below, here is a blog article that covers this issue in more detail: http://www.thebhwgroup.com/blog/2014/08/angularjs-html-form-design-part-2/
推荐答案
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-形式)
To solve the 'dynamic name' problem you need to create an inner form (see ng-form):
<div ng-repeat="social in formData.socials">
<ng-form name="urlForm">
<input type="url" name="socialUrl" ng-model="social.url">
<span class="alert error" ng-show="urlForm.socialUrl.$error.url">URL error</span>
</ng-form>
</div>
另一种方法是编写自定义指令这一点。
The other alternative would be to write a custom directive for this.
下面是的jsfiddle显示ngForm的用法:<一href=\"http://jsfiddle.net/pkozlowski_opensource/XK2ZT/2/\">http://jsfiddle.net/pkozlowski_opensource/XK2ZT/2/
Here is the jsFiddle showing the usage of the ngForm: http://jsfiddle.net/pkozlowski_opensource/XK2ZT/2/
这篇关于如何验证输入动态使用NG-重复创建,NG-展(角)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!