Angular - form validation issues when using the form input directive

I am trying to create a form input directive that will generate form input based on the model and model attributes. For instance,

  • If the field is a name and the type is text, the directive will return an input html control,
  • If the field is a list, it returns a selection field, etc.

These inputs are generated using ng-repeat in the view. The inputs are tied to the model in the area. This is working fine. However, form validation is not performed; those. if the input controls are invalid, the main form still shows that the form is valid.

I set up a simple plunkr to illustrate the problem - http://plnkr.co/edit/R3NTJK?p=preview

NOTE. I really nested the form, since the input field is also dynamically generated from the region model.

I have been trying to deal with this in the last 2 days, and it really makes me crazy.

I'm not sure I missed something.

I would really appreciate it if someone could help me with this.

+4
source share
1 answer

Update : Use the following link function:

link: function linkFn(scope,elem,attr){ var jqLiteWrappedElement = angular.element('<input type="url" name="socialUrl" ng-model="social.url">'); elem.replaceWith(jqLiteWrappedElement); $compile(jqLiteWrappedElement)(scope); } 

Plunker .

For reasons I don’t understand, replaceWith() must be executed before calling the $ compilation. If someone can explain why this is so, we will be grateful for that!

Update2: in the comments below, Artem mentioned that the DOM needs to be changed before calling the bind function, so this also works:

 var myElem = angular.element('some html'); var linkFn = $compile(myElem); element.replaceWith(myElem); linkFn(scope); 

Original answer:

Instead of the link function, just use the template in your directive:

 template: '<input type="url" name="socialUrl" ng-model="social.url">' 
+2
source

Source: https://habr.com/ru/post/1469477/


All Articles