Skip to content

Instantly share code, notes, and snippets.

@davisford
Created November 26, 2014 16:16
Show Gist options
  • Save davisford/004e638421adc7e3dac2 to your computer and use it in GitHub Desktop.
Save davisford/004e638421adc7e3dac2 to your computer and use it in GitHub Desktop.
angular directive for resizing dc.js charts
'use strict';
angular.module('app', ['dc-resize']).controller('ChartCtrl', ['$scope', function ($scope) {
$scope.loading = true;
$scope.charts = {
mychart: dc.rowChart('#mychart')
}
// fetch chart data async then...
$scope.loading = false;
// code to setup rowchart...
}])
/* global _ */ // using lodash or underscore
'use strict'
angular.module('dc-resize').directive('svgResize', ['$window', '$timeout', function ($window, $timeout) {
return {
restrict: 'A',
scope: false, // use parent controller scope
link: function (scope, elem, attrs) {
// ref to dc.js chart obj we hang off; attrs could be like 'netsalesBar', or nested key like 'sales.netsalesBar'
var arr = attrs.chart.split('.'), chart;
if (arr.length === 1) { chart = scope.charts[attrs.chart]; }
else {
chart = [scope.charts].concat(arr).reduce(function (prev, curr) { return prev[curr]; });
}
function resize() {
try {
if (chart.data().length > 0) {
chart.root().select('svg').attr('width', '100%');
$timeout(function () {
if (chart.hasOwnProperty('rescale')) {
chart.rescale();
}
chart.redraw();
}, 100);
}
} catch (err) {
// swallow this error; chart.data() will throw an error if there is no data, or if it isn't ready yet.
// @see https://groups.google.com/d/msg/dc-js-user-group/2pKK_MCNudA/vPEjP9NpKlUJ
}
}
// charts are hidden before the data is loaded, so we
// need to force a resize once they are shown
scope.$watch('loading', function (newval) {
// done loading, so resize
if (newval === false) { resize(); }
});
var lazyResize = _.debounce(resize, 300);
$window.addEventListener('resize', lazyResize);
// make sure to cleanup
scope.$on('$destroy', function () {
$window.removeEventListener('resize', lazyResize);
});
}
};
}])
<div class='dc-chart' id='mychart' ng-controlelr='ChartCtrl' ng-hide='loading'>
<svg svg-resize chart='mychart'></svg>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment