I have a 3rd party library that loads to my page asynchronously and I would like to use it as a service.
How can I wrap the loading code inside an angular service? In general what would be the best practice?
At the moment my approach is something like so:
angular.module('myAPIServices', []).
factory('MyAPI', function () {
return {
\\ API is declared at the loaded script
doStuff:function(){$window.API.doStuff()}
};
});
and then on the page outside of the Angular scope
(function () {
var js = document.createElement('script');
var loc = document.getElementsByTagName('script')[0];
js.async = true;
js.src = "myAPI.js";
loc.parentNode.insertBefore(js, loc);
}());
A posibility is to wrap your library call in $q. This angular service returns a promise, which you can resolve when the library is fully loaded.
Your doStuff
function would be something like:
doStuff: function() {
var deferred = $q.defer();
myAsyncCall().success(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}
In your controller you use the then()
function to process the results.
A second possibility is with a callback. Here is an example of both types.
If your library is manipulating the DOM, it is better to wrap it in a directive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With