Javascript 如何验证使用 ng-repeat、ng-show(角度)动态创建的输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12044277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate inputs dynamically created using ng-repeat, ng-show (angular)
提问by PFranchise
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.
我有一个使用 ng-repeat 创建的表。我想为表中的每个元素添加验证。问题是每个输入单元格都与其上方和下方的单元格具有相同的名称。我试图使用该{{$index}}
值来命名输入,但尽管 HTML 中的字符串文字看起来是正确的,但它现在正在工作。
Here is my code as of now:
这是我现在的代码:
<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.
我试过{{}}
从索引中删除,但这也不起作用。截至目前,输入的验证属性工作正常,但未显示错误消息。
Anyone have any suggestions?
有人有什么建议吗?
Edit: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/
编辑:除了下面的好答案,这里有一篇博客文章更详细地介绍了这个问题:http: //www.thebhwgroup.com/blog/2014/08/angularjs-html-form-design-part-2 /
回答by HoffZ
Since the question was asked the Angular team has solved this issue by making it possible to dynamically create input names.
自从提出这个问题以来,Angular 团队已经通过动态创建输入名称解决了这个问题。
With Angular version 1.3 and lateryou can now do this:
使用Angular 1.3 及更高版本,您现在可以执行以下操作:
<form name="vm.myForm" novalidate>
<div ng-repeat="p in vm.persons">
<input type="text" name="person_{{$index}}" ng-model="p" required>
<span ng-show="vm.myForm['person_' + $index].$invalid">Enter a name</span>
</div>
</form>
Angular 1.3 also introduced ngMessages, a more powerful tool for form validation. You can use the same technique with ngMessages:
Angular 1.3 还引入了 ngMessages,一种更强大的表单验证工具。您可以对 ngMessages 使用相同的技术:
<form name="vm.myFormNgMsg" novalidate>
<div ng-repeat="p in vm.persons">
<input type="text" name="person_{{$index}}" ng-model="p" required>
<span ng-messages="vm.myFormNgMsg['person_' + $index].$error">
<span ng-message="required">Enter a name</span>
</span>
</div>
</form>
回答by pkozlowski.opensource
AngularJS relies on input names to expose validation errors.
AngularJS 依赖于输入名称来暴露验证错误。
Unfortunately, as of today, it is not possible (without using a custom directive) to dynamically generate a name of an input. Indeed, checking input docswe can see that the name attribute accepts a string only.
不幸的是,截至今天,(不使用自定义指令)动态生成输入的名称是不可能的。事实上,检查输入文档我们可以看到 name 属性只接受一个字符串。
To solve the 'dynamic name' problem you need to create an inner form (see ng-form):
要解决“动态名称”问题,您需要创建一个内部表单(请参阅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.
另一种选择是为此编写自定义指令。
Here is the jsFiddle showing the usage of the ngForm: http://jsfiddle.net/pkozlowski_opensource/XK2ZT/2/
这是显示 ngForm 用法的 jsFiddle:http: //jsfiddle.net/pkozlowski_opensource/XK2ZT/2/
回答by Al Johri
If you don't want to use ng-form you can use a custom directive that will change the form's name attribute. Place this directive as an attribute on the same element as your ng-model.
如果您不想使用 ng-form,您可以使用自定义指令来更改表单的 name 属性。将此指令作为属性放在与 ng-model 相同的元素上。
If you're using other directives in conjunction, be careful that they don't have the "terminal" property set otherwise this function won't be able to run (given that it has a priority of -1).
如果您结合使用其他指令,请注意它们没有设置“终端”属性,否则此函数将无法运行(假设它的优先级为 -1)。
For example, when using this directive with ng-options, you must run this one line monkeypatch: https://github.com/AlJohri/bower-angular/commit/eb17a967b7973eb7fc1124b024aa8b3ca540a155
例如,当将此指令与 ng-options 一起使用时,您必须运行这一行monkeypatch:https: //github.com/AlJohri/bower-angular/commit/eb17a967b7973eb7fc1124b024aa8b3ca540a155
angular.module('app').directive('fieldNameHack', function() {
return {
restrict: 'A',
priority: -1,
require: ['ngModel'],
// the ngModelDirective has a priority of 0.
// priority is run in reverse order for postLink functions.
link: function (scope, iElement, iAttrs, ctrls) {
var name = iElement[0].name;
name = name.replace(/\{\{$index\}\}/g, scope.$index);
var modelCtrl = ctrls[0];
modelCtrl.$name = name;
}
};
});
I often find it useful to use ng-init to set the $index to a variable name. For example:
我经常发现使用 ng-init 将 $index 设置为变量名很有用。例如:
<fieldset class='inputs' ng-repeat="question questions" ng-init="qIndex = $index">
This changes your regular expression to:
这会将您的正则表达式更改为:
name = name.replace(/\{\{qIndex\}\}/g, scope.qIndex);
If you have multiple nested ng-repeats, you can now use these variable names instead of $parent.$index.
如果您有多个嵌套的 ng-repeat,您现在可以使用这些变量名称代替 $parent.$index。
Definition of "terminal" and "priority" for directives: https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object
指令的“终端”和“优先级”的定义:https: //docs.angularjs.org/api/ng/service/$compile#directive-definition-object
Github Comment regarding need for ng-option monkeypatch: https://github.com/angular/angular.js/commit/9ee2cdff44e7d496774b340de816344126c457b3#commitcomment-6832095https://twitter.com/aljohri/status/482963541520314369
Github 关于需要 ng-option monkeypatch 的评论:https: //github.com/angular/angular.js/commit/9ee2cdff44e7d496774b340de816344126c457b3#commitcomment-6832095 https://twitter.com/aljohri/status/41436
UPDATE:
更新:
You can also make this work with ng-form.
您也可以使用 ng-form 进行这项工作。
angular.module('app').directive('formNameHack', function() {
return {
restrict: 'A',
priority: 0,
require: ['form'],
compile: function() {
return {
pre: function(scope, iElement, iAttrs, ctrls) {
var parentForm = $(iElement).parent().controller('form');
if (parentForm) {
var formCtrl = ctrls[0];
delete parentForm[formCtrl.$name];
formCtrl.$name = formCtrl.$name.replace(/\{\{$index\}\}/g, scope.$index);
parentForm[formCtrl.$name] = formCtrl;
}
}
}
}
};
});
回答by Al Johri
Use the ng-form directive inside of the tag in which you are using the ng-repeat directive. You can then use the scope created by the ng-form directive to reference a generic name. For example:
在使用 ng-repeat 指令的标签内使用 ng-form 指令。然后,您可以使用 ng-form 指令创建的范围来引用通用名称。例如:
<div class="form-group col-sm-6" data-ng-form="subForm" data-ng-repeat="field in justificationInfo.justifications"">
<label for="{{field.label}}"><h3>{{field.label}}</h3></label>
<i class="icon-valid" data-ng-show="subForm.input.$dirty && subForm.input.$valid"></i>
<i class="icon-invalid" data-ng-show="subForm.input.$dirty && subForm.input.$invalid"></i>
<textarea placeholder="{{field.placeholder}}" class="form-control" id="{{field.label}}" name="input" type="text" rows="3" data-ng-model="field.value" required>{{field.value}}</textarea>
</div>
Credit to: http://www.benlesh.com/2013/03/angular-js-validating-form-elements-in.html
归功于:http: //www.benlesh.com/2013/03/angular-js-validating-form-elements-in.html
回答by Mikita Manko
Added more complex example with "custom validation" on the side of controller http://jsfiddle.net/82PX4/3/
在控制器http://jsfiddle.net/82PX4/3/的一侧添加了带有“自定义验证”的更复杂的示例
<div class='line' ng-repeat='line in ranges' ng-form='lineForm'>
low: <input type='text'
name='low'
ng-pattern='/^\d+$/'
ng-change="lowChanged(this, $index)" ng-model='line.low' />
up: <input type='text'
name='up'
ng-pattern='/^\d+$/'
ng-change="upChanged(this, $index)"
ng-model='line.up' />
<a href ng-if='!$first' ng-click='removeRange($index)'>Delete</a>
<div class='error' ng-show='lineForm.$error.pattern'>
Must be a number.
</div>
<div class='error' ng-show='lineForm.$error.range'>
Low must be less the Up.
</div>
</div>
回答by tomgreen98
Looking over these solutions, the one provided by Al Johri above is the closest to my needs, but his directive was a little less programmable then I wanted. Here is my version of his solutions:
查看这些解决方案,上面 Al Johri 提供的解决方案最接近我的需求,但他的指令比我想要的可编程性要差一些。这是我的解决方案版本:
angular.module("app", [])
.directive("dynamicFormName", function() {
return {
restrict: "A",
priority: 0,
require: ["form"],
compile: function() {
return {
pre: function preLink(scope, iElement, iAttrs, ctrls) {
var name = "field" + scope.$index;
if (iAttrs.dnfnNameExpression) {
name = scope.$eval(iAttrs.dnfnNameExpression);
}
var parentForm = iElement.parent().controller("form");
if (parentForm) {
var formCtrl = ctrls[0];
delete parentForm[formCtrl.$name];
formCtrl.$name = name;
parentForm[formCtrl.$name] = formCtrl;
}
}
}
}
};
});
This solution lets you just pass a name generator expression to the directive and avoids the lock down to pattern substitution he was using.
此解决方案让您只需将名称生成器表达式传递给指令,并避免锁定他正在使用的模式替换。
I also had trouble initially with this solution since it didn't show an example of using it in markup, so here is how I used it.
我最初也遇到了这个解决方案的问题,因为它没有显示在标记中使用它的例子,所以这里是我如何使用它。
<form name="theForm">
<div ng-repeat="field in fields">
<input type="number" ng-form name="theInput{{field.id}}" ng-model="field.value" dynamic-form-name dnfn-name-expression="'theInput' + field.id">
</div>
</form>
I have a more complete working example on github.
我在github上有一个更完整的工作示例。
回答by Vlad Vinnikov
validation is working with ng repeat if I use the following syntax scope.step3Form['item[107][quantity]'].$touched
I don't know it's a best practice or the best solution, but it works
如果我使用以下语法,验证正在使用 ng repeat 我scope.step3Form['item[107][quantity]'].$touched
不知道这是最佳实践还是最佳解决方案,但它有效
<tr ng-repeat="item in items">
<td>
<div class="form-group">
<input type="text" ng-model="item.quantity" name="item[<% item.id%>][quantity]" required="" class="form-control" placeholder = "# of Units" />
<span ng-show="step3Form.$submitted || step3Form['item[<% item.id %>][quantity]'].$touched">
<span class="help-block" ng-show="step3Form['item[<% item.id %>][quantity]'].$error.required"> # of Units is required.</span>
</span>
</div>
</td>
</tr>
回答by ABCD.ca
Building on pkozlowski.opensource's answer, I've added a way to have dynamic input names that also work with ngMessages. Note the ng-init
part on the ng-form
element and the use of furryName
. furryName
becomes the variable name that contains the variable value for the input
's name
attribute.
以 pkozlowski.opensource 的回答为基础,我添加了一种方法来使动态输入名称也适用于ngMessages。注意元素ng-init
上的ng-form
部分和 的使用furryName
。furryName
成为包含input
的name
属性的变量值的变量名称。
<ion-item ng-repeat="animal in creatures track by $index">
<ng-form name="animalsForm" ng-init="furryName = 'furry' + $index">
<!-- animal is furry toggle buttons -->
<input id="furryRadio{{$index}}"
type="radio"
name="{{furryName}}"
ng-model="animal.isFurry"
ng-value="radioBoolValues.boolTrue"
required
>
<label for="furryRadio{{$index}}">Furry</label>
<input id="hairlessRadio{{$index}}"
name="{{furryName}}"
type="radio"
ng-model="animal.isFurry"
ng-value="radioBoolValues.boolFalse"
required
>
<label for="hairlessRadio{{$index}}">Hairless</label>
<div ng-messages="animalsForm[furryName].$error"
class="form-errors"
ng-show="animalsForm[furryName].$invalid && sectionForm.$submitted">
<div ng-messages-include="client/views/partials/form-errors.ng.html"></div>
</div>
</ng-form>
</ion-item>
回答by Ali Adravi
It is too late but might be it can help anyone
为时已晚,但可能可以帮助任何人
- Create unique name for every control
- Validate by using
fromname[uniquname].$error
- 为每个控件创建唯一名称
- 使用验证
fromname[uniquname].$error
Sample code:
示例代码:
<input
ng-model="r.QTY"
class="span1"
name="QTY{{$index}}"
ng-pattern="/^[\d]*\.?[\d]*$/" required/>
<div ng-messages="formName['QTY' +$index].$error"
ng-show="formName['QTY' +$index].$dirty || formName.$submitted">
<div ng-message="required" class='error'>Required</div>
<div ng-message="pattern" class='error'>Invalid Pattern</div>
</div>
See working demo here
回答by Kondal
If your using ng-repeat $index works like this
如果您使用 ng-repeat $index 是这样工作的
name="QTY{{$index}}"
and
和
<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>
we have to show the ng-show in ng-pattern
我们必须以 ng-pattern 显示 ng-show
<span class="alert-error" ng-show="form['QTY' + $index].$error.pattern">
<span class="alert-error" ng-show="form['QTY' + $index].$error.required">