获取输入的ngModelController [英] Getting ngModelController of the input

查看:78
本文介绍了获取输入的ngModelController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要访问输入元素的ngModelController来检查它是否脏或原始.

I need to access ngModelController of input element to check is it dirty or pristine.

我已经设法通过指令来做到这一点,该指令将ngModel的输入捕获到与元素关联的数据对象上,从而使其可从任何地方获取:

I've managed to do it with directive which grabs ngModel of input to data object associated with element, making it obtainable from anywhere:

app.directive("input", [ function () {
    return {
        restrict: "E",
        replace: false,
        scope: false,
        require: "ngModel",
        link: function (scope, element, attrs, ctrls) {
            element.data('ngModelController', ctrls);
        }
    }
}])

我知道可以对其进行修改以将指令作为属性,从而使其与'input'标签的耦合程度降低.

I know it could be modified to make directive as attribute, making it less coupled to 'input' tag.

我将保存的控制器用于表示UI元素且其标记中具有input元素的指令中.我不使用表单,因为这些元素应该在任何dom上下文中都可以工作,并且表单暗示了对层次结构的某些限制.因此,我正在使用ngModelController来检查验证字段所需的一些内容.

I use that saved controllers in directives which represent UI elements and have input elements in their markup. I don't use forms because those elements should work in any dom context, and forms imply certain limitations to hierarchy. So i'm using ngModelController to check some stuff required for validation of fields.

但是还有更好的方法来获取某些输入的ngModelController吗?

But is there any better way to get ngModelController of certain input?

推荐答案

根据我的经验,Angular已经为您提供了此功能.在您要访问ngModelController的指令中,执行以下操作:

In my experience, Angular provides this to you already. In your directive where you want to access the ngModelController, do the following:

app.directive("randomDirective", function() {
  return {
    ...
    require: "ngModel",
    link: function(scope, element, attrs, ctrl) {
      var someInput = element.find('theInput'),
          ngModelCtrlForInput = someInput.data().$ngModelController;
      //Now you can access the ngModel controller for the <input> of the directive
    }
  }
});

这是否是实现这一壮举的最佳方法还有待观察.我还没有更好的答案(但是,如果您知道一个答案,请ping我,让我知道!).

Whether this is the best way to accomplish this feat remains to be seen. I haven't seen any better answers, yet (but if you know of one please ping me and let me know!).

编辑

This answer has some other options, including something similar to:

element.find('theInput').controller('ngModel')

这篇关于获取输入的ngModelController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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