5

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
  • 1
    It seems that this is the only way (to inject), yes Commented Aug 11, 2014 at 0:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I see. This is very helpful, especially the second way illustrated.
0

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

2 Comments

Heh, that's my fault for not being clear. I am aware I can just attach the constant information on the module object itself as you illustrated. What I am wondering is if you can access the information without the: var app.constants = {foo: "bar", test: "123"}; line first.
I gave my 2 cents on the comment on the very top ;) => you have to inject the constant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.