我有一个使用 ng-repeat 创建的表.我想为表中的每个元素添加验证.问题是每个输入单元格与它上面和下面的单元格具有相同的名称.我尝试使用 {{$index}}
值来命名输入,但尽管 HTML 中的字符串文字看起来正确,但它现在正在工作.
I have a table that is created using ng-repeat. 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.
这是我现在的代码:
<tr ng-repeat="r in model.BSM ">
<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>
</tr>
我已尝试从索引中删除 {{}}
,但这也不起作用.到目前为止,输入的验证属性工作正常,但没有显示错误消息.
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.
大家有什么建议吗?
除了下面的精彩答案之外,这里还有一篇博客文章更详细地介绍了这个问题: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.
不幸的是,截至今天,动态生成输入名称是不可能的(不使用自定义指令).事实上,检查 input docs 我们可以看到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-form):
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.
这里是显示 ngForm 用法的 jsFiddle: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-repeat、ng-show (angular) 动态创建的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!