AngularJS:列出所有表单错误 [英] AngularJS: list all form errors
问题描述
背景:我目前正在开发一个带有标签的应用程序;我想列出验证失败的字段/部分,以指导用户在正确的选项卡中查找错误.
所以我尝试利用 form.$error
来做到这一点;但我还没有完全让它工作.
如果验证错误发生在 ng-repeat
中,例如:
<input name="inumber" required ng-model="url"/><br/>
空值导致 form.$error
包含以下内容:
另一方面,如果验证错误发生在这个ng-repeat
之外:
form.$error
对象包含以下内容:
{ "required": [ {} ] }
但是,我希望以下内容:
{ "required": [ {'iname': {} } ] }
关于为什么缺少元素名称的任何想法?
可以在此处找到正在运行的 plunkr:http://plnkr.co/x6wQMp
正如 @c0bra 在评论中指出的form.$error
对象被填充,它只是不喜欢被转储为 JSON.
循环遍历 form.$errors
和它的嵌套对象会得到想要的结果.
<li ng-repeat="(key, errors) in form.$error track by $index"><strong>{{key }}</strong>错误<ul><li ng-repeat="e in errors">{{ e.$name }} 有错误:<strong>{{ key }}</strong>.</li>
所有功劳都归功于 c0bra.
另一种选择是使用 这个问题 为动态创建的输入分配唯一名称.
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.
So I tried to leverage form.$error
to do so; yet I don't fully get it working.
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>
Empty values result in form.$error
containing the following:
{ "required": [ { "inumber": {} }, { "inumber": {} } ] }
On the other hand, if validation errors occur outside this ng-repeat
:
<input ng-model="name" name="iname" required="true" />
The form.$error
object contains the following:
{ "required": [ {} ] }
yet, I'd expect the following:
{ "required": [ {'iname': {} } ] }
Any ideas on why the name of the element is missing?
A running plunkr can be found here: http://plnkr.co/x6wQMp
As @c0bra pointed out in the comments the form.$error
object is populated, it just doesn't like being dumped out as JSON.
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>
All the credit goes to c0bra on this.
Another option is to use one of the solutions from this question to assign unique names to the dynamically created inputs.
这篇关于AngularJS:列出所有表单错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!