blob: ff719059bd77b5e378d1ecf6864cfdb9c0aaec29 [file] [log] [blame]
Jian Lid7a5a742016-02-12 13:51:18 -08001/*!
2 * angular-chart.js
3 * http://jtblin.github.io/angular-chart.js/
4 * Version: 0.8.8
5 *
6 * Copyright 2015 Jerome Touffe-Blin
7 * Released under the BSD license
8 * https://github.com/jtblin/angular-chart.js/blob/master/LICENSE
9 */
10
11(function (factory) {
12 'use strict';
13 if (typeof exports === 'object') {
14 // Node/CommonJS
15 module.exports = factory(
16 typeof angular !== 'undefined' ? angular : require('angular'),
17 typeof Chart !== 'undefined' ? Chart : require('chart.js'));
18 } else if (typeof define === 'function' && define.amd) {
19 // AMD. Register as an anonymous module.
20 define(['angular', 'chart'], factory);
21 } else {
22 // Browser globals
23 factory(angular, Chart);
24 }
25}(function (angular, Chart) {
26 'use strict';
27
28 Chart.defaults.global.responsive = true;
29 Chart.defaults.global.multiTooltipTemplate = '<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value %>';
30
31 Chart.defaults.global.colours = [
32 '#97BBCD', // blue
33 '#DCDCDC', // light grey
34 '#F7464A', // red
35 '#46BFBD', // green
36 '#FDB45C', // yellow
37 '#949FB1', // grey
38 '#4D5360' // dark grey
39 ];
40
41 var usingExcanvas = typeof window.G_vmlCanvasManager === 'object' &&
42 window.G_vmlCanvasManager !== null &&
43 typeof window.G_vmlCanvasManager.initElement === 'function';
44
45 if (usingExcanvas) Chart.defaults.global.animation = false;
46
47 return angular.module('chart.js', [])
48 .provider('ChartJs', ChartJsProvider)
49 .factory('ChartJsFactory', ['ChartJs', '$timeout', ChartJsFactory])
50 .directive('chartBase', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory(); }])
51 .directive('chartLine', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('Line'); }])
52 .directive('chartBar', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('Bar'); }])
53 .directive('chartRadar', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('Radar'); }])
54 .directive('chartDoughnut', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('Doughnut'); }])
55 .directive('chartPie', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('Pie'); }])
56 .directive('chartPolarArea', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('PolarArea'); }]);
57
58 /**
59 * Wrapper for chart.js
60 * Allows configuring chart js using the provider
61 *
62 * angular.module('myModule', ['chart.js']).config(function(ChartJsProvider) {
63 * ChartJsProvider.setOptions({ responsive: true });
64 * ChartJsProvider.setOptions('Line', { responsive: false });
65 * })))
66 */
67 function ChartJsProvider () {
68 var options = {};
69 var ChartJs = {
70 Chart: Chart,
71 getOptions: function (type) {
72 var typeOptions = type && options[type] || {};
73 return angular.extend({}, options, typeOptions);
74 }
75 };
76
77 /**
78 * Allow to set global options during configuration
79 */
80 this.setOptions = function (type, customOptions) {
81 // If no type was specified set option for the global object
82 if (! customOptions) {
83 customOptions = type;
84 options = angular.extend(options, customOptions);
85 return;
86 }
87 // Set options for the specific chart
88 options[type] = angular.extend(options[type] || {}, customOptions);
89 };
90
91 this.$get = function () {
92 return ChartJs;
93 };
94 }
95
96 function ChartJsFactory (ChartJs, $timeout) {
97 return function chart (type) {
98 return {
99 restrict: 'CA',
100 scope: {
101 data: '=?',
102 labels: '=?',
103 options: '=?',
104 series: '=?',
105 colours: '=?',
106 getColour: '=?',
107 chartType: '=',
108 legend: '@',
109 click: '=?',
110 hover: '=?',
111
112 chartData: '=?',
113 chartLabels: '=?',
114 chartOptions: '=?',
115 chartSeries: '=?',
116 chartColours: '=?',
117 chartLegend: '@',
118 chartClick: '=?',
119 chartHover: '=?'
120 },
121 link: function (scope, elem/*, attrs */) {
122 var chart, container = document.createElement('div');
123 container.className = 'chart-container';
124 elem.replaceWith(container);
125 container.appendChild(elem[0]);
126
127 if (usingExcanvas) window.G_vmlCanvasManager.initElement(elem[0]);
128
129 ['data', 'labels', 'options', 'series', 'colours', 'legend', 'click', 'hover'].forEach(deprecated);
130 function aliasVar (fromName, toName) {
131 scope.$watch(fromName, function (newVal) {
132 if (typeof newVal === 'undefined') return;
133 scope[toName] = newVal;
134 });
135 }
136 /* provide backward compatibility to "old" directive names, by
137 * having an alias point from the new names to the old names. */
138 aliasVar('chartData', 'data');
139 aliasVar('chartLabels', 'labels');
140 aliasVar('chartOptions', 'options');
141 aliasVar('chartSeries', 'series');
142 aliasVar('chartColours', 'colours');
143 aliasVar('chartLegend', 'legend');
144 aliasVar('chartClick', 'click');
145 aliasVar('chartHover', 'hover');
146
147 // Order of setting "watch" matter
148
149 scope.$watch('data', function (newVal, oldVal) {
150 if (! newVal || ! newVal.length || (Array.isArray(newVal[0]) && ! newVal[0].length)) return;
151 var chartType = type || scope.chartType;
152 if (! chartType) return;
153
154 if (chart) {
155 if (canUpdateChart(newVal, oldVal)) return updateChart(chart, newVal, scope, elem);
156 chart.destroy();
157 }
158
159 createChart(chartType);
160 }, true);
161
162 scope.$watch('series', resetChart, true);
163 scope.$watch('labels', resetChart, true);
164 scope.$watch('options', resetChart, true);
165 scope.$watch('colours', resetChart, true);
166
167 scope.$watch('chartType', function (newVal, oldVal) {
168 if (isEmpty(newVal)) return;
169 if (angular.equals(newVal, oldVal)) return;
170 if (chart) chart.destroy();
171 createChart(newVal);
172 });
173
174 scope.$on('$destroy', function () {
175 if (chart) chart.destroy();
176 });
177
178 function resetChart (newVal, oldVal) {
179 if (isEmpty(newVal)) return;
180 if (angular.equals(newVal, oldVal)) return;
181 var chartType = type || scope.chartType;
182 if (! chartType) return;
183
184 // chart.update() doesn't work for series and labels
185 // so we have to re-create the chart entirely
186 if (chart) chart.destroy();
187
188 createChart(chartType);
189 }
190
191 function createChart (type) {
192 if (isResponsive(type, scope) && elem[0].clientHeight === 0 && container.clientHeight === 0) {
193 return $timeout(function () {
194 createChart(type);
195 }, 50, false);
196 }
197 if (! scope.data || ! scope.data.length) return;
198 scope.getColour = typeof scope.getColour === 'function' ? scope.getColour : getRandomColour;
199 scope.colours = getColours(type, scope);
200 var cvs = elem[0], ctx = cvs.getContext('2d');
201 var data = Array.isArray(scope.data[0]) ?
202 getDataSets(scope.labels, scope.data, scope.series || [], scope.colours) :
203 getData(scope.labels, scope.data, scope.colours);
204 var options = angular.extend({}, ChartJs.getOptions(type), scope.options);
205 chart = new ChartJs.Chart(ctx)[type](data, options);
206 scope.$emit('create', chart);
207
208 // Bind events
209 cvs.onclick = scope.click ? getEventHandler(scope, chart, 'click', false) : angular.noop;
210 cvs.onmousemove = scope.hover ? getEventHandler(scope, chart, 'hover', true) : angular.noop;
211
212 if (scope.legend && scope.legend !== 'false') setLegend(elem, chart);
213 }
214
215 function deprecated (attr) {
216 if (typeof console !== 'undefined' && ChartJs.getOptions().env !== 'test') {
217 var warn = typeof console.warn === 'function' ? console.warn : console.log;
218 if (!! scope[attr]) {
219 warn.call(console, '"%s" is deprecated and will be removed in a future version. ' +
220 'Please use "chart-%s" instead.', attr, attr);
221 }
222 }
223 }
224 }
225 };
226 };
227
228 function canUpdateChart (newVal, oldVal) {
229 if (newVal && oldVal && newVal.length && oldVal.length) {
230 return Array.isArray(newVal[0]) ?
231 newVal.length === oldVal.length && newVal.every(function (element, index) {
232 return element.length === oldVal[index].length; }) :
233 oldVal.reduce(sum, 0) > 0 ? newVal.length === oldVal.length : false;
234 }
235 return false;
236 }
237
238 function sum (carry, val) {
239 return carry + val;
240 }
241
242 function getEventHandler (scope, chart, action, triggerOnlyOnChange) {
243 var lastState = null;
244 return function (evt) {
245 var atEvent = chart.getPointsAtEvent || chart.getBarsAtEvent || chart.getSegmentsAtEvent;
246 if (atEvent) {
247 var activePoints = atEvent.call(chart, evt);
248 if (triggerOnlyOnChange === false || angular.equals(lastState, activePoints) === false) {
249 lastState = activePoints;
250 scope[action](activePoints, evt);
251 scope.$apply();
252 }
253 }
254 };
255 }
256
257 function getColours (type, scope) {
258 var colours = angular.copy(scope.colours ||
259 ChartJs.getOptions(type).colours ||
260 Chart.defaults.global.colours
261 );
262 while (colours.length < scope.data.length) {
263 colours.push(scope.getColour());
264 }
265 return colours.map(convertColour);
266 }
267
268 function convertColour (colour) {
269 if (typeof colour === 'object' && colour !== null) return colour;
270 if (typeof colour === 'string' && colour[0] === '#') return getColour(hexToRgb(colour.substr(1)));
271 return getRandomColour();
272 }
273
274 function getRandomColour () {
275 var colour = [getRandomInt(0, 255), getRandomInt(0, 255), getRandomInt(0, 255)];
276 return getColour(colour);
277 }
278
279 function getColour (colour) {
280 return {
281 fillColor: rgba(colour, 0.2),
282 strokeColor: rgba(colour, 1),
283 pointColor: rgba(colour, 1),
284 pointStrokeColor: '#fff',
285 pointHighlightFill: '#fff',
286 pointHighlightStroke: rgba(colour, 0.8)
287 };
288 }
289
290 function getRandomInt (min, max) {
291 return Math.floor(Math.random() * (max - min + 1)) + min;
292 }
293
294 function rgba (colour, alpha) {
295 if (usingExcanvas) {
296 // rgba not supported by IE8
297 return 'rgb(' + colour.join(',') + ')';
298 } else {
299 return 'rgba(' + colour.concat(alpha).join(',') + ')';
300 }
301 }
302
303 // Credit: http://stackoverflow.com/a/11508164/1190235
304 function hexToRgb (hex) {
305 var bigint = parseInt(hex, 16),
306 r = (bigint >> 16) & 255,
307 g = (bigint >> 8) & 255,
308 b = bigint & 255;
309
310 return [r, g, b];
311 }
312
313 function getDataSets (labels, data, series, colours) {
314 return {
315 labels: labels,
316 datasets: data.map(function (item, i) {
317 return angular.extend({}, colours[i], {
318 label: series[i],
319 data: item
320 });
321 })
322 };
323 }
324
325 function getData (labels, data, colours) {
326 return labels.map(function (label, i) {
327 return angular.extend({}, colours[i], {
328 label: label,
329 value: data[i],
330 color: colours[i].strokeColor,
331 highlight: colours[i].pointHighlightStroke
332 });
333 });
334 }
335
336 function setLegend (elem, chart) {
337 var $parent = elem.parent(),
338 $oldLegend = $parent.find('chart-legend'),
339 legend = '<chart-legend>' + chart.generateLegend() + '</chart-legend>';
340 if ($oldLegend.length) $oldLegend.replaceWith(legend);
341 else $parent.append(legend);
342 }
343
344 function updateChart (chart, values, scope, elem) {
345 if (Array.isArray(scope.data[0])) {
346 chart.datasets.forEach(function (dataset, i) {
347 (dataset.points || dataset.bars).forEach(function (dataItem, j) {
348 dataItem.value = values[i][j];
349 });
350 });
351 } else {
352 chart.segments.forEach(function (segment, i) {
353 segment.value = values[i];
354 });
355 }
356 chart.update();
357 scope.$emit('update', chart);
358 if (scope.legend && scope.legend !== 'false') setLegend(elem, chart);
359 }
360
361 function isEmpty (value) {
362 return ! value ||
363 (Array.isArray(value) && ! value.length) ||
364 (typeof value === 'object' && ! Object.keys(value).length);
365 }
366
367 function isResponsive (type, scope) {
368 var options = angular.extend({}, Chart.defaults.global, ChartJs.getOptions(type), scope.options);
369 return options.responsive;
370 }
371 }
372}));