如何在指令(angularjs)中设置有效性 [英] How to set validity in directive (angularjs)

查看:23
本文介绍了如何在指令(angularjs)中设置有效性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在指令中设置输入有效性?指令模板中的输入.

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

假设我有模板:

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

我的指令是这样的:

.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.

推荐答案

您需要检索 NgModelController 与输入关联的实例.然后你在这个对象上调用 $setValidity 指定验证键(required、minlength、customkey 等).它看起来像这样:

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

    }
  }
})

这里最重要的部分是如何获取NgModelController.下面的代码行正在处理它:

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

这篇关于如何在指令(angularjs)中设置有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆