AngularJS 动态表单字段验证 [英] AngularJS dynamic form field validation
问题描述
我正在尝试验证从后端端点提供给我的一些表单字段...
I am trying to validate some form fields which are given to me from a backend endpoint...
所以基本上 input
元素是在 ng-repeat
中动态创建的.所以input
属性也是动态添加的,比如type
、name
等...
So basically the input
elements are dynamically created inside a ng-repeat
.
Therefore, the input
attributes are also dynamically added, such as the type
, name
, etc...
但是因为name
属性是动态添加的,所以当我尝试验证它时,像这样,例如:
However because the name
attribute is dynamically added, when I try to validate it, like this, for example:
myForm.elName.$valid
它不返回任何东西,因为此时它不知道 elName
是什么.
It doesn't return anything because at this point, it doesn't know what elName
is.
我创建了一个 jsFiddle 来演示这个问题:http://jsfiddle.net/peduarte/HB7LU/1889/
I created a jsFiddle to demonstrate the problem: http://jsfiddle.net/peduarte/HB7LU/1889/
任何帮助或建议将不胜感激!
Any help or advice will be much appreciated!
FANX.
我一直在参考这个很棒的文档:http://docs.angularjs.org/api/ng.directive:input.email
推荐答案
试试我的自定义指令:
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);
}
};
});
使用它:
<input dynamic-name="field.name"
type="{{ field.type }}"
placeholder="{{ field.name }}"
ng-model="field.value"
required>
问题说明:
默认情况下,使用 ngModelController (ng-model
) 的输入元素在链接到注册自身并在 上公开属性时调用
带有输入的 name 属性,在本例中为 FormController.$addControl
FormController{{ field.name }}
.因此,即使控件已注册但您没有在名为 email
, firstName
的 FormController
上公开属性,您只有 {{ field.name }}
引用最后一个输入项
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. 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
解决方案说明:
在这个解决方案中,我创建了一个自定义指令来在运行时用正确的名称替换 {{ field.name }}
.
In this solution, I created a custom directive to replace the {{ field.name }}
with the correct name at runtime.
有关为什么我必须使用 terminal:true,
和 priority:1000
的更多信息,请查看此讨论:从AngularJS中的指令添加指令
For more information why I have to use terminal:true,
and priority:1000
, check out this discussion: Add directives from directive in AngularJS
这篇关于AngularJS 动态表单字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!