Validating form in user directive ...?

I have an HTML form that is dynamically created from the given “product” and the fields that it has, allowing the user to modify the associated data. I use the custom "editor" directive to handle the creation of HTML elements necessary for the user to update data.

An example can be seen here: http://plnkr.co/edit/2fAVVpwTHFgxwTq4eAMI

First off, I'm not sure if this is the best way to achieve this, but it (so far) seems to be working fine. (Any other idea is welcome!)

However, I want to add validation rules for controls, for example. require so that a message appears when the input is left blank. I tried to add these validation rules to the code (as seen from the template in the directive), but it never works. I am almost sure that something is connected with me because I get my passages with areas somewhere ... AngularJS Batarang shows an object on the main sphere:

 form: { {{fieldName}}: {} } 

Which is clearly wrong (and nonsense!)

+4
source share
2 answers

Wrap the template in your own ng form:

 textTemplate = '<div ng-form="editor">' + '<input id="{{fieldName}}" name="{{fieldName}}" type="text" ng-model="fieldData.data" required>' + '<div ng-show="editor.$dirty && editor.$invalid">Invalid:' + '<span ng-show="editor.$error.required">Some validation error!</span>' + '</div>' + '</div>'; 

The problem that you are facing is that when you create an isolation region (scope {...}) you do not have access to the parent form or to any parent region. IMO, this is definitely good since you do not want your directive to hardcode the name of the parent form, and it saves your directive as a standalone unit.

Code: http://plnkr.co/edit/qCjs16tuwVjSNzJdkk71?p=preview

+15
source

Instead of checking form[fieldName].$dirty && form[fieldName].$invalid just check for a model value

so textTemplate looks below

 textTemplate = '<input id="{{fieldName}}" name="{{fieldName}}" type="text" ng-model="fieldData.data">' + '<div ng-show="!fieldData.data">Invalid:' + '<span ng-show="!fieldData.data">Some validation error!</span>' + '</div>'; 

see updated change http://plnkr.co/edit/BvXkGxA0GlGip7KLXUup?p=preview

-3
source

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


All Articles