Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

javascript - How to set validity in directive (angularjs)

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:

<input type="text" ng-model="someObj.val" ng-change="check()">

And my directive is like:

.directive('myDir', function () {
      return {
        restrict: 'E',
        templateUrl: 'trmplate.html',
        link: function (scope) {

          someObj = {val: '123'};

          scope.check = function () {
            var result = false;
            myInput.$setValidity(result); //this is didn't work, $setValidity not a function
          };

        }
      }
    })

I'm cannot wrap it with form, because the idea behind it is to allow user to include this input inside user's form.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...