我使用指令为我的项目生成各种Google Charts。这个平台对我来说是新手,我很感激有人看一下这段代码,并告诉我这是否是生成和更新图表的最佳方法。
如您所见,我在条形图和圆环图上有两个$ watch语句。目前,我有一个调用方法来刷新数据的按钮...这将在未来自动化。
myApp.directive('gChart', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs) {
var myChartType = attrs.charttype || "bar";
var chart = " ";
if( myChartType == "line" ) {
chart = new google.visualization.LineChart(elm[0]);
}
else if ( myChartType == "bar" ) {
scope.$watch('barData', function(){
console.log('barData changed');
chart = new google.visualization.BarChart(elm[0]);
chart.draw(scope.barData, scope.barOptions);
});
}
else if ( myChartType == "column" ) {
chart = new google.visualization.ColumnChart(elm[0]);
}
else if ( myChartType == "timeline" ) {
chart = new google.visualization.Timeline(elm[0]);
chart.draw(scope.timelineData, scope.timelineOptions);
}
else if ( myChartType == "donut" ) {
scope.$watch('donutData', function(){
console.log('donutData changed');
chart = new google.visualization.PieChart(elm[0]);
chart.draw(scope.donutData, scope.donutOptions);
});
}
}
}
});
HTML用法:
<div g-chart chartType="bar"></div>
<div g-chart chartType="donut"></div>
<div g-chart chartType="timeline"></div>
它似乎运作良好,但是我还有很多关于AngularJS的东西我还没有学习!