Skip to content

Instantly share code, notes, and snippets.

@davisford
Created July 26, 2014 19:59
Show Gist options
  • Save davisford/cc7815000a78029b08dc to your computer and use it in GitHub Desktop.
Save davisford/cc7815000a78029b08dc to your computer and use it in GitHub Desktop.
svg resize angular directive for dc.js
/* global _, d3 */
'use strict';
angular.module('app.warehouse')
/**
* directive to make the charts responsive (at least for the widths);
* chart heights are typically fixed. Use this directive like so:
* <div id='mychart'>
* <svg svg-resize chart='ref-to-dc-chart' selector='mychart' loading='loading'>
* </div>
*
* attributes:
* chart: this is angular scope ref to the dc chart
* selector: this is name of parent selector id
* loading: scope boolean that tracks if data is loading or not
*
* A bit convoluted, but I tried a number of alternative things to make the
* markup not so hideous, but had very little luck
*/
.directive('svgResize', ['$window', function($window) {
return {
restrict: 'A',
scope: { chart: '=', loading: '=' },
link: function (scope, elem, attrs) {
$window.chart = scope.chart;
function resize() {
if (scope.chart.data().length > 0) {
d3.select(attrs.selector + ' svg')
.attr('width', '100%');
if (scope.chart.hasOwnProperty('rescale')) {
scope.chart.rescale();
}
scope.chart.redraw();
}
}
// 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);
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment