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?
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?
Share Improve this question asked Sep 15, 2014 at 23:09 FrontierPsychoFrontierPsycho 7439 silver badges25 bronze badges 1- i don't see why not- just pass it at the appropriate time. – Daniel A. White Commented Sep 15, 2014 at 23:15
1 Answer
Reset to default 9You 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.