Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - wrapping 3rd party asynchronic loaded library as a service

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);
}());
like image 500
Shlomi Schwartz Avatar asked Jan 01 '13 08:01

Shlomi Schwartz


1 Answers

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.

like image 88
asgoth Avatar answered Nov 08 '22 04:11

asgoth