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?

Share Improve this question asked Aug 11, 2014 at 0:24 TrazeKTrazeK 8381 gold badge8 silver badges18 bronze badges 1
  • 1 It seems that this is the only way (to inject), yes – Mik378 Commented Aug 11, 2014 at 0:38
Add a ment  | 

2 Answers 2

Reset to default 13

Assuming, 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:

  1. 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');
    
  2. 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