[英]Angularjs - Calling a controller function inside directive
我正在嘗試將jQuery Sparkline圖表與Angularjs一起使用。 我要顯示多個圖表,因此我決定在控制器中創建一個函數,並為每個圖表(指令)調用它。
JS
調節器
.controller('sparklineCtrl', [function(){
this.sparklineBar = function(id, values, height, barWidth, barColor, barSpacing) {
$('.'+id).sparkline(values, {
type: 'bar',
height: height,
barWidth: barWidth,
barColor: barColor,
barSpacing: barSpacing
})
}
}])
指示
.directive('sparklineBar', function(){
return {
restrict: 'A',
scope: {
slBar: '&'
},
link: function(scope, element) {
scope.slBar('stats-bar', [6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], '45px', 3, '#fff', 2);
}
}
})
HTML
<div data-ng-controller="sparklineCtrl as spctrl">
<div class="chart" id="stats-bar" data-sparkline-bar data-sl-bar="spctrl.sparklineBar()"></div>
</div>
運行上面的代碼,在瀏覽器控制台中沒有錯誤,但根本沒有呈現圖表。 我不知道我的代碼有什么問題。 當我嘗試將函數的代碼直接放在指令中時,它正在工作。
.directive('sparklineBar', function(){
return {
restrict: 'A',
link: function(scope, element) {
$('#stats-bar').sparkline([6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], {
type: 'bar',
height: 45,
barWidth: 3,
barColor: '#fff',
barSpacing: 2
})
}
}
})
我不想使用上述方式,因為我需要多個圖表。 請幫助我使用控制器功能解決此問題。
最好將功能邏輯移到服務/工廠,然后在指令中使用注入。
例:
app.factory('sparkService', function () {
var ss = {} ;
ss.slBar= function(id, values, height, barWidth, barColor, barSpacing) {
$('.'+id).sparkline(values, {
type: 'bar',
height: height,
barWidth: barWidth,
barColor: barColor,
barSpacing: barSpacing
});
};
return ss;
}
在指令中
.directive('sparklineBar', ['sparkService',function(sparkService){
return {
restrict: 'A',
scope: {
slBar: '&'
},
link: function(scope, element) {
sparkService.slBar('stats-bar', [6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], '45px', 3, '#fff', 2);
}
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.