How to set validity in directive (angularjs)

前端 未结 2 849
抹茶落季
抹茶落季 2020-12-17 07:03

Is there a way to set an input validity inside a directive? The input present in the directive\'s template.

Lets say I have template:



        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 07:34

    You need to retrieve NgModelController instance associated with the input. Then you call $setValidity on this object specifying validation key (required, minlength, customkey, etc.). It will look like this:

    .directive('myDir', function() {
      return {
        restrict: 'E',
        template: '',
        link: function(scope, element) {
    
          var modelController = element.find('input').controller('ngModel');
    
          someObj = {
            val: '123'
          };
    
          scope.check = function() {
            var result = false;
            modelController.$setValidity('myrequired', result);
          };
    
        }
      }
    })
    

    The most important part here is how to get NgModelController. Below line of code is taking care of it:

    var modelController = element.find('input').controller('ngModel');
    

提交回复
热议问题