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

后端 未结 5 1414
[愿得一人]
[愿得一人] 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:53

    You can create a new component which including control with all required validators. Your component would look like:

    
    

    All required logic component should keep inside. To do it, create the my-control directive with template. Inside the template you can place an input with validation attributes:

    
    

    Then you need to bind ng-model value on your component to input:

    angular.module('app', []).directive('myControl', function() {
       return {
           restrict: 'E',
           require: 'ngModel', //import ngModel into linking function
           templateUrl: 'myControl.tpl',
           scope: {}, //our component can have private properties, isolate it
           link: function(scope, elm, attrs, ngModel) {
               // reflect model changes via js
               ngModel.$render = function() {
                   scope.value = ngModel.$viewValue;
               };
               // update model value after changes in input
               scope.$watch('value', function(value) {
                   ngModel.$setViewValue(value);
               });
           }
       };
    });
    

    Here is a demo when you can see this component in action and how it works.

提交回复
热议问题