admin管理员组文章数量:1416320
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.
本文标签: javascriptAngularJSwrapping 3rd party asynchronic loaded library as a serviceStack Overflow
版权声明:本文标题:javascript - AngularJS - wrapping 3rd party asynchronic loaded library as a service - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745249120a2649713.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论