我正在嘗試將jQuery Sparkline圖表與Angularjs一起使用。我有多個圖表要顯示,所以我決定在控制器中創建一個函數,併爲每個圖表(指令)調用它。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
})
}
}
})
我不想使用上述方式,因爲我需要多個圖表。請幫我使用控制器功能來解決這個問題。
指令給你查看在'element'這將是jQuery對象時之前的角度被包括在頁面的jQuery。使用它來代替id選擇器。 jQuery不屬於控制器,而是將數據傳入指令 – charlietfl
在指令中指定您的控制器。 'controller:'sparklineCtrl',controllerAs:'spctrl'' – HankScorpio