Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Angular constant outside of angular

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.

like image 310
Narek Mamikonyan Avatar asked Jul 22 '14 07:07

Narek Mamikonyan


Video Answer


2 Answers

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.

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

like image 143
dfsq Avatar answered Oct 20 '22 19:10

dfsq


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 :)

like image 44
SM Adnan Avatar answered Oct 20 '22 19:10

SM Adnan