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

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

问题描述

有没有一种方法来设置一个指令内输入的有效性?
输入present在指令中的模板。

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 此对象指定的验证密钥(需要使用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。低于code线是照顾它:

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天全站免登陆