我找到了这个帖子How to handle multiple JS libraries with different loading times in Angular?我用它来将 d3.js 添加到我的标题中。我现在还必须添加 d3.legend.js。我将如何以回调方式完成此任务?
var d3js = angular.module('d3', []);
d3js.factory('d3Service', ['$document', '$q', '$rootScope', '$window',
function($document, $q, $rootScope, $window) {
var d = $q.defer();
function onScriptLoad() {
// Load client in the browser
$rootScope.$apply(function() { d.resolve($window.d3); });
}
// Create a script tag with d3 as the source
// and call our onScriptLoad callback when it
// has been loaded
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = 'lib/d3.v3.js';
scriptTag.onreadystatechange = function () {
if (this.readyState == 'complete') onScriptLoad();
}
scriptTag.onload = onScriptLoad;
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);
//this is now where I have to add d3.legend.js which depends on the successful loading of d3.js.
return {
d3: function() { return d.promise; }
};
}]);
最佳答案
原始想法的简化版本:
var app = angular.module('SomeApp', []);
app.factory('LibraryFactory', function () {
var factory = {};
factory.getD3 = function(callback) {
if(!window.d3) {
var script = document.createElement("script");
script.src = "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.9/d3.min.js";
document.head.appendChild(script);
script.onload = function() {
callback(window.d3);
};
} else {
callback(window.d3);
}
};
factory.getD3Legend = function(callback) {
if(!window.d3.legend) {
//...ditto
}
};
return factory;
});
要使用工厂(例如,在 Controller 中),您可以链接调用:
app.controller('SomeTrialCtrl', function ($scope, LibraryFactory) {
LibraryFactory.getD3(function (d3) {
LibraryFactory.getD3Legend(function (d3WithLegend) {
// place code using the libraries here
});
});
});
或者在 d3.legend 的情况下,factory.getD3Legend 函数可以在内部调用 getD3 函数以使事情变得更简单。喜欢:
factory.getD3Legend = function(callback) {
factory.getD3(function(d3) {
if(!d3.legend) {
//...ditto
}
callback(d3);
}
};
无论如何,这就是基本思想。 @aarosil 在原始帖子中的答案可能更符合 Angular。
关于javascript - Angular JS - 添加相互依赖的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31337385/