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
Add a ment  | 

1 Answer 1

Reset to default 4

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.

本文标签: javascriptAngularJSwrapping 3rd party asynchronic loaded library as a serviceStack Overflow