因爲似乎是在網絡上沒有可行的解決方案至今,我希望這可以幫助某個人真實存在。關鍵概念是將js
文件加載和圖表組件初始化與callback
延遲。
加載js文件的服務:
app.service('gchart', ['$window', '$q', '$rootScope', function ($window, $q, $rootScope) {
var deferred = $q.defer();
//run when the jsapi is loaded
$window.callback = function() {
$window.google.load('visualization','1',{
packages: ['corechart'],
callback: function() {
//again having a callback to wait for the visualization to load
$rootScope.$apply(function() {
deferred.resolve();
});
}
});
}
// dynamically adding the js file on page access
var script = document.createElement('script');
script.src = '//www.google.com/jsapi?callback=callback';
document.body.appendChild(script);
return deferred.promise;
}]);
使用的指令:
app.directive(.., ['gchart', function(.., gchart) {
return {
//...
link: function(scope, elm, attr) {
scope.init = function() {
var viz = new google.visualization.arrayToDataTable(data);
//add options, linechart, draw, whatever
};
// delay the creation until jsapi files loaded
loadGoogleChartAPI.then(function() {
scope.init();
}, function() {
//ignore
});
}
}
}
是'addEventListener'獨立瀏覽器嗎? IE,Chrome,FF,Opera? – membersound
@membersound for IE你可以檢查這個,http://stackoverflow.com/a/6927800/3279156更多關於兼容性檢查:http://caniuse.com/#feat=addeventlistener – sreeramu