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

查看:24
本文介绍了获取输入的 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);
        }
    }
}])

我知道可以修改它以将指令作为属性,从而减少与输入"标签的耦合.

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

这是否是实现这一壮举的最佳方式还有待观察.我还没有看到任何更好的答案(但如果你知道一个,请联系我并告诉我!).

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