【发布时间】:2015-07-29 08:03:45
【问题描述】:
我正在尝试将 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
})
}
}
})
我不想使用上述方式,因为我需要多个图表。请帮助我使用控制器功能解决此问题。
【问题讨论】:
-
指令让您可以访问
element,当 jQuery 包含在 Angular 之前的页面中时,这将是 jQuery 对象。使用它而不是 id 选择器。 jQuery 不属于控制器,而是将数据传递给指令 -
在指令中指定你的控制器。
controller: 'sparklineCtrl', controllerAs: 'spctrl'
标签: javascript angularjs angularjs-directive