Looking for an efficient method to factorize an Angular Directive designed for displaying charts.
After exploring various solutions, I discovered a neat way to implement a directive that showcases a single chart flawlessly.
How can I utilize the same directive for showcasing different charts? Each chart requires a JSON object containing settings and data for rendering.
Avoid cluttering the Angular View with excessive JSON input passed through the directive.
Specifics:-
- Every chart shares certain key/value pairs that can be included in the directive.
- How do I integrate chart-specific key & value pairs into each directive?
E.g. - One chart featuring green bars while the other displays red lines.
Angular Directive
(function () {
'use strict';
angular
.module("analytics")
.directive("angularDirectiveAmcharts", angularDirectiveAmcharts);
function angularDirectiveAmcharts() {
var directive = {
link: link,
restrict: 'A',
replace: true,
scope: {
chartdata: '=',
type: '=',
customstyle: '@',
chartsettings: '=',
chartid: '@'
},
template: '<div id="{{ chartid }}" style="{{ customstyle }}"></div>'
};
return directive;
function link(scope, elem, attrs) {
AmCharts.makeChart(scope.chartid, {
"type": "serial",
"categoryField": "date",
"autoMarginOffset": 10,
"marginRight": 20,
"marginTop": 20,
//Omitted some key-value pairs for brevity
"dataProvider": scope.chartdata
});
}
}
})();
View
<div class="chartarea" ng-controller="pcController as vm">
<div angular-directive-amcharts chartid="chartdiv" chartdata="vm.chart_data"></div>
</div>
Prioritizing maintainability as there will be numerous modifications post-internship completion.