在角度中,如何加载存储在变量" async2Url"中的url。在" asyncurl"中的网址后面的脚本负载?请注意,async2Url依赖于asyncurl响应的内容,然后指令才能使用它。
我目前正在使用以下代码加载单个脚本" asyncUrl",我如何使其成为" asyncUrl"和" async2url"在撤回承诺之前加载(一个接一个)?:
// Google async initializer needs global function, so we use $window
angular.module('GoogleMapsInitializer')
.factory('Initializer', function($window, $q){
// maps loader deferred object
var mapsDefer = $q.defer();
// Google's url for async maps initialization accepting callback function
var asyncUrl = 'https://maps.googleapis.com/maps/api/js?callback=';
var async2Url = 'https://urltoseconscript/script2.js';
// async loader
var asyncLoad = function(asyncUrl, callbackName) {
var script = document.createElement('script');
//script.type = 'text/javascript';
script.src = asyncUrl + callbackName;
document.body.appendChild(script);
};
// callback function - resolving promise after maps successfully loaded
$window.googleMapsInitialized = function () {
mapsDefer.resolve();
};
// loading google maps
asyncLoad(asyncUrl, 'googleMapsInitialized');
return {
// usage: Initializer.mapsInitialized.then(callback)
mapsInitialized : mapsDefer.promise
};
})
在指令中,我包括:
Initializer.mapsInitialized.
.then(function(){
map = new google.maps.Map(element, options);
});
如果我能保留指令中的内容,只需改变" GoogleMapsInitializer"的内容。模块,这将是最好的。如果能够轻松支持说第三个依赖于第一个(或第二个)的脚本,那就更好了。如果不能保留而不更改我当前在指令代码中的内容,那么最好的方法是什么?
答案 0 :(得分:1)
这个版本怎么样
angular.module('GoogleMapsInitializer').factory('Initializer', function($window, $q) {
// Google's url for async maps initialization accepting callback function
var asyncUrl = 'https://maps.googleapis.com/maps/api/js?callback=';
var async2Url = 'https://urltoseconscript/script2.js';
// async loader
var asyncLoad = function(asyncUrl, callbackName) {
var deferred = $q.defer();
var script = document.createElement('script');
if (callbackName) {
$window[callbackName] = deferred.resolve;
asyncUrl += callbackName;
}
else {
script.onload = deferred.resolve;
}
script.src = asyncUrl;
document.body.appendChild(script);
return deferred.promise;
};
// loading google maps
var mapsPromise = asyncLoad(asyncUrl, 'googleMapsInitialized').then(function() {
return asyncLoad(async2Url);
});
return {
// usage: Initializer.mapsInitialized.then(callback)
mapsInitialized: mapsPromise
};
});
检查我为测试装载机设置的小演示。