Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  9] [ 1]  / answers: 1 / hits: 19712  / 11 Years ago, thu, january 30, 2014, 12:00:00

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


More From » angularjs

 Answers
9

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


[#72841] Wednesday, January 29, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yvettel

Total Points: 517
Total Questions: 101
Total Answers: 102

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
;