admin管理员组文章数量:1287647
I have the following lines:
var app = angular.module('app', []);
app.constant("const", {
foo: "bar",
test: "123"
});
I would like to now access the information in constant
directly from the module app
. Something like this didn't work:
console.log(app.constant.const.foo);
I know you can inject constants into controllers, services etc and access the information but for my purposes, I would like to access them straight off the module.
Is the only way to access a registered constant
is to inject it into a controller/service/etc?
I have the following lines:
var app = angular.module('app', []);
app.constant("const", {
foo: "bar",
test: "123"
});
I would like to now access the information in constant
directly from the module app
. Something like this didn't work:
console.log(app.constant.const.foo);
I know you can inject constants into controllers, services etc and access the information but for my purposes, I would like to access them straight off the module.
Is the only way to access a registered constant
is to inject it into a controller/service/etc?
- 1 It seems that this is the only way (to inject), yes – Mik378 Commented Aug 11, 2014 at 0:38
2 Answers
Reset to default 13Assuming, somehow, you want an access to the const
outside the angularjs environment.
Then you have to retrieve it from an injector
, and there are two ways you can get the injector:
Get the current injector of a running angularjs application like this:
var injector = angular.element(document).injector(); // assuming `ng-app` is on the document injector.get('const');
Create a new injector from existing modules:
var injector = angular.injector(['ng', 'app']); // note the 'ng' module is required this way injector.get('const');
Example Plunker: http://plnkr.co/edit/ld7LLlr94N7PiqnxY5zH
Hope this helps.
If you really want to access the constant directly, you could do:
var app = angular.module('app', []);
var app.constants = {foo: "bar", test: "123"};
app.constant("const", app.constants);
console.log(app.constants.foo);
But, I don't see a real benefit ;)
本文标签: javascriptAccess constant directly from Angular moduleStack Overflow
版权声明:本文标题:javascript - Access constant directly from Angular module - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741244562a2364624.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论