How to set validity in directive (angularjs)

前端 未结 2 839
抹茶落季
抹茶落季 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:16

    You don't need to use elem in order to get the controller, just add it as a param to the link function, and set require to ['ngModel'] in order to get the model ctrl.

     require: ['ngModel'],
     link: function (scope, elem, attrs, ctrl) {
    
          someObj = {val: '123'};
    
          scope.check = function () {
            var result = false;
            ctrl.$setValidity(result);
          };
    
        }
    
    0 讨论(0)
  • 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: '<input type="text" ng-model="someObj.val" ng-change="check()">',
        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');
    
    0 讨论(0)
提交回复
热议问题