Can I programmatically apply Angular validation directives inside a custom directive?

后端 未结 5 1390
[愿得一人]
[愿得一人] 2020-12-29 20:05

I have found great many occurrences of the following pattern for html inputs, this being for phone numbers:



        
5条回答
  •  别那么骄傲
    2020-12-29 20:52

    One way to do this (i.e. apply existing validators without writing their code again) would be to add the validation directives' respective attributes and force a re-compile. This would require your directive to have a high-enough priority and also be terminal: true.

    app.directive("bkNgValidation", function($compile){
      return {
        priority: 10000,
        terminal: true,
        link: function(scope, element){
          element.attr("ng-required", "true");
          element.attr("ng-minlength", 20);
          element.attr("ng-maxlength", 30);
    
          // prevent infinite loop
          element.removeAttr("bk-ng-validation");
    
          $compile(element)(scope);
        }
      };
    });
    

    Demo

提交回复
热议问题