Use Angular constant outside angular

I know that it is not recommended to use Angular services outside of Angular, but nevertheless it is very interesting for me, for example, I have .constant('APIprefix','/api')

How can I get the APIprefix value outside the Angular scope? For example, from another js file that is not in the Angular scope.

+8
javascript angularjs
source share
2 answers

You can access any service, for example:

 angular.element(document.documentElement).injector().get('APIprefix'); 

Note that you should go to angular.element DOM node where you put ng-app . In the above document.documentElement example there is an HTML tag.

Demo: http://plnkr.co/edit/nf8zhDsl1PAnE5zDYYaG?p=preview

+11
source share
Example

pixelbits did not work for me. I needed to make a little change to do this.

Recording Constants

 var app = angular.module('module',[]); app.constant('APIprefix', '/api'); 

Reading from Angular

 var prefix = angular.injector(['ng', 'module']).get('APIprefix'); 

Thanks pixelbits for showing me the way :)

+7
source share

All Articles