Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add validation attributes in an angularjs directive

I am trying to write an angular directive that adds validation attributes to the tag, but it doesn't seem to be working. Here is my demo. You will notice that "Is Valid" remains true if you delete the text in the second input box, but goes to false if you delete the text in the first input box.

http://plnkr.co/edit/Rr81dGOd2Zvio1cLYW8D?p=preview

Here is my directive:

angular.module('demo', [])
.directive('metaValidate', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.attr("required", true);
        }
    };
});

I'm guessing I am just missing something simple.

like image 671
Leslie Hanks Avatar asked Sep 20 '13 23:09

Leslie Hanks


People also ask

What is $setValidity in AngularJS?

The $setValidity() function is a built-in AngularJS function that is used to assign a key/value combination that can be used to check the validity of a specific model value. The key in this case is “unique” and the value is either true or false.


1 Answers

All rules for validation of the form are being read in compilation phase of the form, so after making changes in a child node, you need to recompile form directive (form it's a custom directive in AngularJS). But do it only once, avoid infinite loops (your directive's 'link' function will be called again after form's compilation).

angular.module('demo', [])
.directive('metaValidate', function ($compile) {
    return {
        restrict: 'A',
        link: function (scope,element, attrs) {
          if (!element.attr('required')){
            element.attr("required", true);
            $compile(element[0].form)(scope);
          }
        }
    };
});

Working plunker: http://plnkr.co/edit/AB6extu46W4gFIHk0hIl?p=preview

like image 174
OZ_ Avatar answered Nov 01 '22 19:11

OZ_