Skip to content

Instantly share code, notes, and snippets.

@owenmead
Created May 3, 2013 17:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owenmead/5511756 to your computer and use it in GitHub Desktop.
Save owenmead/5511756 to your computer and use it in GitHub Desktop.
angular.module('myApp').directive('myChart', function () {
var draw_line_chart = function(scope) { ... }
var draw_bar_chart = function(scope) { ... }
var setup_chart_interactions = function(scope) { ... }
// other helper functions ...
return {
templateUrl: '/views/my-chart.html',
restrict: 'E',
scope: {
chart_queries: '=ngModel',
chart_type: '=chartType'
},
// Controller shared with all instansiated directives
controller: ['$scope', 'chartData', function($scope, chartData) {
var updateChart = function() {
if ($scope.chart_type === 'time_line') {
chartData.getChartData($scope.chart_queries).then(function(data) {
draw_line_chart($scope, data);
setup_chart_interactions($scope);
});
} else {
chartData.getAggregateData($scope.chart_queries).then(function(data) {
draw_bar_chart($scope, data);
setup_chart_interactions($scope);
});
}
};
return {
updateChart: updateChart
};
}],
// Compile function: manipulate the DOM
compile: function() {
// Linking function: One for each directive. Setup each chart
return function postLink(scope, iElement, iAttrs, controller) {
scope.svg = d3.select(iElement.find('g')[0]);
scope.$watch('chart_queries', function(queries) {
if (queries === undefined || queries.length === 0) {
draw_empty_chart(scope);
} else {
controller.updateChart();
}
}, true); // Test for equality rather then reference
scope.chart_type = scope.chart_type || 'time_line';
scope.$watch('chart_type', function(new_val, old_val) {
if (new_val === old_val) {
// No update if value the same
return;
}
controller.updateChart();
});
};
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment