I'm trying to use jQuery Sparkline charts with Angularjs. I have multiple charts to display, so I've decided to create a function in the controller and call it for each chart(directive).
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
.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>
Running the above code there is no error in browser console but it's not rendering the chart at all. I don't know what is wrong in my code. When I try to place function's code directly inside directive, it's working.
.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
})
}
}
})
I don't want to use the above way as I need multiple charts. Please help me fix this using controller functions.
elementwhich will be jQuery object when jQuery is included in page before angular. Use that instead of id selector. jQuery doesn't belong in controller, pass data into directive insteadcontroller: 'sparklineCtrl', controllerAs: 'spctrl'