拥有以下是不错的做法:
例如,我有一个模板,我需要创建~16个图表(Highcharts / amCharts)。所有这些都没有相同的配置和串行数据。
1选项示例:
angular.module('myApp')
.directive('ngHighcharts', () => ({
restrict: 'AE',
replace: 'true',
scope: {
data: '='
},
template: '<div></div>',
link: function(scope, $elem, $attrs) {
var chart, config;
config = {
chart: {
renderTo: $elem[0],
type: $attrs.type ? $attrs.type : 'bar'
},
exporting: {
enabled: $attrs.exporting ? $attrs.exporting : false
},
title: {
text: $attrs.title ? $attrs.title : ''
},
xAxis: {
categories: $attrs.categories ? $attrs.categories : data[0]
},
tooltip: {
valueSuffix: $attrs.valueSuffix ? $attrs.valueSuffix : ''
},
plotOptions: {
bar: {
dataLabels: {
enabled: $attrs.dataLabels ? $attrs.dataLabels : false
}
}
},
series: scope.data
};
chart = new Highcharts.Chart(config);
scope.$on('$destroy', function () {
scope.$evalAsync(function () {
chart.destroy ();
});
});
}
}));
2选项示例:
angular.module('myApp')
.directive('ngHighcharts', () => ({
restrict: 'AE',
replace: 'true',
scope: {
config: '=',
data: '='
},
template: '<div></div>',
link: function(scope, $elem, $attrs) {
config.chart.renderTo = $elem[0];
var chart = new Highcharts.Chart(config);
scope.$on('$destroy', function () {
scope.$evalAsync(function () {
chart.destroy ();
});
});
}
}));
3选项示例:
angular.module('myApp')
.directive('ngHighcharts', () => ({
restrict: 'AE',
replace: 'true',
scope: {
data: '='
},
template: '<div></div>',
link: function(scope, $elem, $attrs) {
var chart, config;
config = {
chart: {
renderTo: $elem[0],
type: 'bar'
},
exporting: {
enabled: true
},
title: {
text: $attrs.title ? $attrs.title : ''
},
xAxis: {
categories: $attrs.categories ? $attrs.categories : data[0]
},
tooltip: {
valueSuffix: $attrs.valueSuffix ? $attrs.valueSuffix : ''
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
series: scope.data
};
chart = new Highcharts.Chart(config);
scope.$on('$destroy', function () {
scope.$evalAsync(function () {
chart.destroy ();
});
});
}
}));
在这种情况下,最佳做法是什么?