【问题标题】:How can I access a directive's ngModelController from another directive?如何从另一个指令访问指令的 ngModelController?
【发布时间】:2014-08-13 02:02:05
【问题描述】:

如何从另一个指令访问指令的ngModelController

场景

我正在创建一个 type ahead 小部件,它由 typeAhead 指令和 autoCompletePopUp 指令组成。 AutoCompletePopUp 指令将使用 typeAhead's controllertypeAhead 交互。

但是当一个项目被选中时,我不知道如何从autoCompletePopUp 调用typeAhead's $setViewValue

【问题讨论】:

标签: angularjs angularjs-directive


【解决方案1】:

为什么不为typeAhead 的控制器添加一个函数,该函数在其自身上调用 $setViewValue。在typeAhead's 控制器的上下文中,您应该可以访问范围。如果需要,您可以将 typeAhead 的 ngModelController 放在作用域上。像这样的:

angular.module("myModule").directive("typeAhead", function() {
   return {
      require: "ngModel",
      controller: function($scope) {
         this.setValue = function(value) {
            $scope.ngModelController.$setViewValue(value);
         };
      },
      link: function(scope, element, attributes, ngModelController) {
         scope.ngModelController = ngModelController;
      },
   };
});

angular.module("myModule").directive("typeAhead", function() {
   return {
      require: "typeAhead",
      link: function(scope, element, attributes, typeAheadController) {
         scope.someAction = function(value) {
            typeAheadController.setValue(value);
         };
      },
   };
});

(防止缩小并根据需要将控制器移动到单独的对象/文件中;为方便起见,在此处内联)

【讨论】:

  • 谢谢。我怎么能错过呢?
猜你喜欢
  • 2016-06-17
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 2014-09-06
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多