获取输入的ngModelController

set*_*tec 4 angularjs angularjs-directive

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

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

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

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

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

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

Ste*_*e J 5

以我的经验,Angular已经为您提供了。在要访问ngModelController的指令中,执行以下操作:

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
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

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

编辑

这个答案还有其他一些选择,包括类似于:

element.find('theInput').controller('ngModel')
Run Code Online (Sandbox Code Playgroud)