AngularJS:列出所有表格错误 [英] AngularJS: list all form errors
问题描述
背景: 我目前正在使用带标签的应用程序;并且我想列出未通过验证的字段/部分,以指导用户在右侧选项卡中查找错误.
Background: I am currently working on an application with tabs; and I'd like to list the fields / sections that fail validation, to direct the user to look for errors in the right tab.
所以我试图利用form.$error
来做到这一点;但是我还没有完全正常工作.
So I tried to leverage form.$error
to do so; yet I don't fully get it working.
如果ng-repeat
内部发生验证错误,例如:
If validation errors occur inside a ng-repeat
, e.g.:
<div ng-repeat="url in urls" ng-form="form">
<input name="inumber" required ng-model="url" />
<br />
</div>
空值导致form.$error
包含以下内容:
Empty values result in form.$error
containing the following:
{ "required": [
{
"inumber": {}
},
{
"inumber": {}
}
] }
另一方面,如果在ng-repeat
之外发生验证错误:
On the other hand, if validation errors occur outside this ng-repeat
:
<input ng-model="name" name="iname" required="true" />
form.$error
对象包含以下内容:
{ "required": [ {} ] }
但是,我希望以下几点:
yet, I'd expect the following:
{ "required": [ {'iname': {} } ] }
关于缺少元素名称的任何想法吗?
Any ideas on why the name of the element is missing?
可以在这里找到正在运行的plunkr: http://plnkr.co/x6wQMp
A running plunkr can be found here: http://plnkr.co/x6wQMp
推荐答案
如 @ c0bra 所述, form.$error
对象已填充,只是不喜欢将其作为JSON丢弃.
As @c0bra pointed out in the comments the form.$error
object is populated, it just doesn't like being dumped out as JSON.
循环遍历form.$errors
及其嵌套对象将获得所需的结果.
Looping through form.$errors
and it's nested objects will get the desired result however.
<ul>
<li ng-repeat="(key, errors) in form.$error track by $index"> <strong>{{ key }}</strong> errors
<ul>
<li ng-repeat="e in errors">{{ e.$name }} has an error: <strong>{{ key }}</strong>.</li>
</ul>
</li>
</ul>
所有功劳归功于 c0bra .
Another option is to use one of the solutions from this question to assign unique names to the dynamically created inputs.
这篇关于AngularJS:列出所有表格错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!