Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use AngularJS's $q outside an Angular component?

I am writing a browser app, and I have a file that creates an object and initializes it. The app is written in AngularJS, but the file in question is plain Javascript, outside the Angular ecosystem.

I want to use promises in that file, but since Angular contains an an implementation of Q, I'd rather just use that than bring in another library.

I am also using RequireJS.

So, is there a way to use $q in a non-Angular file?

like image 262
FrontierPsycho Avatar asked Sep 15 '14 23:09

FrontierPsycho


1 Answers

You can do this by using the angular.injector() method which returns an $injector function that can be injected with dependencies that you need (e.g. $http, $q) through its invoke() method.

DEMO

Something like this:

angular.injector(['ng']).invoke(['$q', function($q) {

  $q.when('hello world').then(function(message) {
    window.alert(message);
  });

}]);

Note that the array passed to angular.injector() is a list of modules, I included the ng module because that is where the AngularJS core dependencies are located.

like image 185
ryeballar Avatar answered Sep 18 '22 11:09

ryeballar