我正在尝试将 jQuery Sparkline 图表与 Angularjs 结合使用。我有多个图表要显示,因此我决定在 Controller 中创建一个函数并为每个图表(指令)调用它。
JS
Controller
.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
})
}
}
})
我不想使用上述方式,因为我需要多个图表。请帮助我使用 Controller 功能解决此问题。
最佳答案
最好将函数逻辑移至服务/工厂,然后在指令中使用注入(inject)。
示例:
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);
}
}]);
关于javascript - Angularjs - 在指令内调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30292670/