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);
}());
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);
}());
Share
Improve this question
edited Sep 15, 2015 at 17:22
Mogsdad
45.8k21 gold badges163 silver badges286 bronze badges
asked Jan 1, 2013 at 8:22
Shlomi SchwartzShlomi Schwartz
8,91330 gold badges120 silver badges198 bronze badges
1 Answer
Reset to default 4A 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745249121a4618568.html
评论列表(0条)