[英]AngularJS dynamic form field validation
I am trying to validate some form fields which are given to me from a backend endpoint... 我正在尝试验证从后端端点给我的一些表单字段...
So basically the input
elements are dynamically created inside a ng-repeat
. 所以基本上
input
元素是在ng-repeat
中动态创建的。 Therefore, the input
attributes are also dynamically added, such as the type
, name
, etc... 因此,
input
属性也会动态添加,例如type
, name
等......
However because the name
attribute is dynamically added, when I try to validate it, like this, for example: 但是因为
name
属性是动态添加的,所以当我尝试验证它时,例如:
myForm.elName.$valid
It doesn't return anything because at this point, it doesn't know what elName
is. 它不会返回任何内容,因为此时它不知道
elName
是什么。
I created a jsFiddle to demonstrate the problem: http://jsfiddle.net/peduarte/HB7LU/1889/ 我创建了一个jsFiddle来演示这个问题: http : //jsfiddle.net/peduarte/HB7LU/1889/
Any help or advice will be much appreciated! 任何帮助或建议将不胜感激!
FANX. FANX。
EDIT: 编辑:
I've been referring to this AWESOME documentation: http://docs.angularjs.org/api/ng.directive:input.email 我一直在提到这个AWESOME文档: http ://docs.angularjs.org/api/ng.directive: input.email
Try my custom directive: 试试我的自定义指令:
myApp.directive("dynamicName",function($compile){
return {
restrict:"A",
terminal:true,
priority:1000,
link:function(scope,element,attrs){
element.attr('name', scope.$eval(attrs.dynamicName));
element.removeAttr("dynamic-name");
$compile(element)(scope);
}
};
});
Use it: 用它:
<input dynamic-name="field.name"
type="{{ field.type }}"
placeholder="{{ field.name }}"
ng-model="field.value"
required>
Explanation of the problem: 问题解释:
By default, input elements using ngModelController ( ng-model
) call FormController.$addControl
when they are linked to register itself and expose a property on the FormController
with the name property of the input which is {{ field.name }}
in this case. 默认情况下,输入元素使用ngModelController(
ng-model
)调用FormController.$addControl
当它们被链接到注册本身并在FormController
使用输入的name属性公开属性,在这种情况下为{{ field.name }}
。 Therefore, even though the control is registered but you don't have exposed properties on FormController
with named email
, firstName
, you only have {{ field.name }}
referencing the last input item 因此,即使注册了控件但在
FormController
使用命名email
firstName
公开属性,也只有{{ field.name }}
引用最后一个输入项
Explanation of the solution: 解决方案的解释:
In this solution, I created a custom directive to replace the {{ field.name }}
with the correct name at runtime. 在此解决方案中,我创建了一个自定义指令,以便在运行时将
{{ field.name }}
替换为正确的名称。
For more information why I have to use terminal:true,
and priority:1000
, check out this discussion: Add directives from directive in AngularJS 有关为什么我必须使用
terminal:true,
和priority:1000
更多信息,请查看此讨论: 在AngularJS中添加指令中的指令
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.