最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use Angular constant outside of angular - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Oct 24, 2016 at 16:33 Avag Sargsyan 2,5234 gold badges32 silver badges45 bronze badges asked Jul 22, 2014 at 7:27 Narek MamikonyanNarek Mamikonyan 4,6112 gold badges26 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

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

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

发布评论

评论列表(0)

  1. 暂无评论