Skip to content

Instantly share code, notes, and snippets.

@jperelli
Last active August 29, 2015 14:28
Show Gist options
  • Save jperelli/ad25787176612b25896e to your computer and use it in GitHub Desktop.
Save jperelli/ad25787176612b25896e to your computer and use it in GitHub Desktop.

This is a simple autoupdating angular directive to show sparklines in html. Changes on data will auto reflect in GUI.

Requires angularjs and highcharts or highstock.

Usage in html

<span hc-sparkline="data"></span>

in controller

$scope.data = [100, 150, 110, 120, 283, 121]
// or
$scope.data = '100,150,110,120,283,121'
angular.module('hc-sparkline', [])
.directive('hcSparkline', [function () {
'use strict';
return {
restrict: 'A',
scope: {
hcSparkline: '='
},
link: function (scope, elem, attrs, ngModel) {
var chart = false;
scope.$watch('hcSparkline', function (newData, oldData) {
if ( newData != oldData ) {
var model;
if ( angular.isString(newData) )
model = newData.replace(/(^,)|(,$)/g, "");
else
model = newData;
var data;
// Make sure we have an array of numbers
if (typeof model != 'undefined') {
if (angular.isArray(model) )
data = model;
else
data = model.split(',');
}
render(data);
}
}, true);
var render = function (data) {
if (!chart) {
chart = $(elem).highcharts('SparkLine', {
series: [{
data: data,
pointStart: 1
}]
});
chart = chart.highcharts();
}
else {
chart.series[0].setData(angular.copy(data), false);
}
chart.redraw();
};
}
};
}])
.run(function () { // instance-injector
// this comes directly from http://www.highcharts.com/demo/sparkline
Highcharts.SparkLine = function (options, callback) {
var defaultOptions = {
chart: {
renderTo: (options.chart && options.chart.renderTo) || this,
backgroundColor: null,
borderWidth: 0,
type: 'area',
margin: [2, 0, 2, 0],
width: 120,
height: 20,
style: {
overflow: 'visible'
},
skipClone: true
},
title: {
text: ''
},
credits: {
enabled: false
},
xAxis: {
labels: {
enabled: false
},
title: {
text: null
},
startOnTick: false,
endOnTick: false,
tickPositions: []
},
yAxis: {
endOnTick: false,
startOnTick: false,
labels: {
enabled: false
},
title: {
text: null
},
tickPositions: [0]
},
legend: {
enabled: false
},
tooltip: {
backgroundColor: null,
borderWidth: 0,
shadow: false,
useHTML: true,
hideDelay: 0,
shared: true,
padding: 0,
positioner: function (w, h, point) {
return { x: point.plotX - w / 2, y: point.plotY - h};
}
},
plotOptions: {
series: {
animation: false,
lineWidth: 1,
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
marker: {
radius: 1,
states: {
hover: {
radius: 2
}
}
},
fillOpacity: 0.25
},
column: {
negativeColor: '#910000',
borderColor: 'silver'
}
}
};
options = Highcharts.merge(defaultOptions, options);
return new Highcharts.Chart(options, callback);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment