简体   繁体   English

如何在指令(AngularJS)中设置有效性

[英]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. 我无法将其包装在表单中,因为其背后的想法是允许用户将此输入包含在用户的表单中。

You need to retrieve NgModelController instance associated with the input. 您需要检索与输入关联的NgModelController实例。 Then you call $setValidity on this object specifying validation key (required, minlength, customkey, etc.). 然后,在此对象上调用$setValidity setValidity,指定验证密钥(必需,minlength,customkey等)。 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. 这里最重要的部分是如何获取NgModelController。 Below line of code is taking care of it: 下面的代码行正在处理它:

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

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. 您不需要使用elem即可获取控制器,只需将其作为参数添加到链接函数中,然后将require设置为['ngModel']即可获取模型ctrl。

 require: ['ngModel'],
 link: function (scope, elem, attrs, ctrl) {

      someObj = {val: '123'};

      scope.check = function () {
        var result = false;
        ctrl.$setValidity(result);
      };

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM