如果该指令使用'require',是否有办法将指令的控制器注入其链接函数?

时间:2014-12-11 12:42:54

标签: angularjs angularjs-directive

如果指令在指令定义对象集中没有require属性,那么传递给link的第4个参数就是该指令的控制器。

如果我们设置require,那么第4个属性是我们require的控制器(或控制器数组),并且指令失去了对它自己的引用控制器。访问此内容的最佳方式是什么?

angular.module 'example', []

.directive 'directive1', ->
  restrict: 'E'

  controller: ($log)->
    @sayHi = -> $log.info('hi')

  link: (scope, element, attributes, controller)->
    controller.sayHi() # works.

.directive 'directive2', ->
  restrict: 'A'
  require: 'directive1'
  controller: ($log)->
    @sayBye = -> $log.info('bye')

  link: (scope, element, attributes, controller)->
    controller.sayHi() # works
    # how would I access sayBye?

我意识到我可以将sayBye放在$scope上,并通过链接功能中的scope进行访问,但有没有办法做到这一点,不会&#39} ; 涉及范围?

这是唯一的方法吗?

.directive 'directive2', ->
  ownCtrl = {}

  restrict: 'A'
  require: 'directive1'
  controller: ($log)->
    @sayBye = -> $log.info('bye')
    ownCtrl = this

  link: (scope, element, attributes, controller)->
    controller.sayHi() # works
    ownCtrl.sayBye()

1 个答案:

答案 0 :(得分:4)

您可以要求一系列控制器,包括指令的控制器本身。正如$compile documentation中提供的评论中提到的那样。



angular.module('demo', [])

  .directive('directive1', function() {
    return {
      controller: function() {
        this.sayHello = function(directiveName) {
          console.log(directiveName + ' says hi');
        };
      },
      link: function(scope, elem, attr, ctrl) {
        ctrl.sayHello('directive1');
      }
    };
  })

  .directive('directive2', function() {
    return {
      require: ['^directive1', 'directive2'],
      controller: function() {
        this.sayGoodbye = function() {
          console.log('goodbye');
        };
      },
      link: function(scope, elem, attr, ctrls) {
        var d1Ctrl = ctrls[0],
            d2Ctrl = ctrls[1];
        
        d1Ctrl.sayHello('directive2');
        d2Ctrl.sayGoodbye();
      }
    };
  });

<div ng-app="demo">
  <div directive1>
    <div directive2></div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
&#13;
&#13;
&#13;