I know it is not a good practice to use Angular services outside of angular but nevertheless it's very interesting for me, for example I have
.constant('APIprefix','/api')
how can I retrieve APIprefix value outside of angular scope? For instance from other js file which is not in angular scope.
You can access any service like this:
angular.element(document.documentElement).injector().get('APIprefix');
Note that you should pass to angular.element
DOM node where you put ng-app
. In the example above document.documentElement
is HTML tag.
pixelbits example did not worked for me. I needed to do a small change to do it.
Writting constants
var app = angular.module('module',[]);
app.constant('APIprefix', '/api');
Reading from non angular scope
var prefix = angular.injector(['ng', 'module']).get('APIprefix');
Thanks pixelbits for showing me the way :)
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