How to add validation attributes in an angularjs directive

后端 未结 3 1379
天命终不由人
天命终不由人 2020-12-17 17:27

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\

3条回答
  •  -上瘾入骨i
    2020-12-17 18:12

    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

提交回复
热议问题