Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  50] [ 4]  / answers: 1 / hits: 85161  / 10 Years ago, fri, july 18, 2014, 12:00:00

Is it possible to inject a constant into another constant with AngularJS?



e.g.



var app = angular.module('myApp');

app.constant('foo', { message: Hello } );

app.constant('bar', ['foo', function(foo) {
return {
message: foo.message + ' World!'
}
}]);


I need the use of an angular constant because I need to inject this into a config routine. i.e.



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


I know that you can only inject constants and providers into config routines, and my understanding is that you can do dependency injection into providers, however, it does not seem to be the best method for this sort of scenario...



Thanks in advance for your help!


More From » angularjs

 Answers
27

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.


[#70150] Thursday, July 17, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
addie

Total Points: 699
Total Questions: 89
Total Answers: 97

Location: Cayman Islands
Member since Fri, Mar 4, 2022
2 Years ago
;