【问题标题】:Is there a way to inject a directive's controller into its link function if that directive uses 'require'?如果指令使用'require',有没有办法将指令的控制器注入其链接函数?
【发布时间】:2014-12-11 12:42:54
【问题描述】:

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

如果我们设置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 进行访问,但是有什么方法可以做到这一点涉及范围?

这是唯一的方法吗?

.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()

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您可以要求一个控制器数组,包括指令的控制器本身。如$compile documentation中提供的cmets中所述。

    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>

    【讨论】:

    • 我知道数组,不敢相信我没有尝试将当前指令名称放入其中!感谢你的回答。 PS 也从未在答案中看到内联可运行的 sn-ps - 我非常喜欢它!
    猜你喜欢
    • 2016-01-26
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多