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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With