AngularJS constants AngularJS constants angularjs angularjs

AngularJS constants


You are correct, it's impossible to register both foo and bar as constants.

Also for using a provider as a workaround, you almost got it right except that you have to store data in a provider instance:

var app = angular.module('myApp', []);app.constant('foo', {    message: 'Hello'});app.provider('bar', ['foo', function(foo) {  this.data = {    message: foo.message + ' World!'  };  this.$get = function() {    return this.data;  };}]);

and then in config block, inject a bar's provider instance (not a bar instance as it isn't available yet in the config phase):

app.config(['barProvider', function(barProvider) {  console.log(barProvider.data.message);}]);

Hope this helps.


Another approach is to use Immediately-invoked function expression to define a function and invoke it immediately. This way, the expression evaluates and returns the value of the function, which can consist of two constants.

This is achievable using something similar to this:

app.constant("foo", (function() {    var message = 'Hello'    return {        foo: message,        bar: message + " World!"    }})());

and then use the constants like:

console.log("foo: " + foo.foo);console.log("bar: " + foo.bar);


It seems the best way to approach this is to make the second constant a provider. i.e.

var app = angular.module('myApp');app.constant('foo', { message: "Hello" } );app.provider('bar', ['foo', function(foo) {     this.$get = function() {         return {             message: foo.message + ' World!'         };    } }]);

and then:

app.config(['bar', function(bar) {    console.log(bar.message);}]);