我想制作两个元素指令barchart
和bar
,如下所示:
<barchart>
<bar ng-repeat='row in some_table'
label='row.date | date'
height='row.profit' />
</barchart>
我已经有一些javascript会在给定(label, height)
对的画布元素上绘制相应的图形。获取barchart
指令以从bar
指令的attrs中读取值的正确方法是什么?
答案 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