mindparse February 2016

Is it possible to access constants without injection?

I am using gulp-ng-config in my project to dynamically generate some constants at build time.

This is working just fine, but it got me and a colleague thinking about how constants are accessed in an angular app.

If you want to access constants in controllers that are defined on the same module that the constants belong to, do you still have to inject the constants by name to the controllers so you can access their values?

Looking at various examples, I'm pretty sure this is the only way - just wondered if there was some other way that didn't require a further dependency to be injected.

Answers


Patrick Kelleter February 2016

The constants injection is part of a best-practice-approach. It's just a syntactical overhead preventing you from doing bad stuff like defining global variables and using them all over the place. Of course you still can go ahead and define variables on the global window-scope and use them everywhere, but i cleary wouldn't suggest to do so.

So you can do

window.foo = 123;

and somewhere else

alert (window.foo);

this will show the wanted value but, of course, this is very bad practice.

You can also define variables on the angular $rootScope and use them anywhere. Yet, bottom line this is nothing else than defining them on window scope and shouldn't be done as well.

The last option (and probably the best for your scenario) is to define one constant OBJECT containing some more values. This way you just have to inject one constant object instead of many different ones.

Say you have two constants so far $width = 1024 $height = 768

there is nothing bad about defining one injectable constant

$config = { width: 1024, height: 768 };

if you just want to access the $constant from outside the angular world you can always do it like this:

angular.element('body').injector().get('$constant')

assuming you declared your ng-app on the 'body' element or even further outside (like the 'html' element).


Walfrat February 2016

This is what dependency injection is made for : to force you to show all dependencies to your model.

Otherwise you can use the injector and use the method $get to get the values but i don't recommend it.

A last way would be to use a provider to store all constants and inject only the resulting service. However this will mask from which module each constants come from.

Post Status

Asked in February 2016
Viewed 1,314 times
Voted 5
Answered 2 times

Search




Leave an answer