如何在嵌套元素指令之间进行通信?

时间:2013-09-20 20:06:17

标签: angularjs angularjs-directive

我想制作两个元素指令barchartbar,如下所示:

<barchart>
  <bar ng-repeat='row in some_table'
       label='row.date | date'
       height='row.profit' />
</barchart>

我已经有一些javascript会在给定(label, height)对的画布元素上绘制相应的图形。获取barchart指令以从bar指令的attrs中读取值的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

假设您的示例是您的问题的简化,以下是您可以在这两个指令之间进行通信的方式:

app.directive('barchart', function($log) {
  return {
    restrict: 'EA',
    controller: function($scope) {
      this.drawBar = function(height, date) {
        $log.log('[barchart] Handling charting of bar with label ' + date + ' and height ' + height + '.');
      };
    },
    link: function(scope, element, attrs) {
      $log.log('[barchart] Doing DOM transformations...')
    }
  };
});

app.directive('bar', function($log) {
  return {
    restrict: 'EA',
    require: '^barchart', // Require an immediate parent element of barchart
    // Requiring the barchart directive gives us access to the bar chart controller instance.
    link: function(scope, element, attrs, barchartCntrl) {
      barchartCntrl.drawBar(scope.row.height, scope.row.date);
    }
  };
});

工作plunker