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
.
Therefore, the input
attributes are also dynamically added, such as the type
, name
, etc...
However because the name
attribute is dynamically added, when I try to validate it, like this, for example:
myForm.elName.$valid
It doesn't return anything because at this point, it doesn't know what elName
is.
I created a jsFiddle to demonstrate the problem: http://jsfiddle.net/peduarte/HB7LU/1889/
Any help or advice will be much appreciated!
FANX.
EDIT:
I've been referring to this AWESOME documentation:
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>
DEMO
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. 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
Explanation of the solution:
In this solution, I created a custom directive to replace the {{ field.name }}
with the correct name at runtime.
For more information why I have to use terminal:true,
and priority:1000
, check out this discussion: Add directives from directive in AngularJS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With