Is there a way to define a constant in Angular that depends on another constant being passed to it? See this example:
angular
.constant("names", ["Bob", "Jane"])
.constant("friends", ["names", getFriends]);
function getFriends(names) {
var friends = {};
names.forEach(function(name) {
friends[name] = { firstName: name };
});
return friends;
}
The names
constant defines an array of names passed to a function to generate object literals.
While this code doesn't work as expected, is there a way to achieve this concept? One approach could be like this...
var names = ["Bob", "Jane"];
angular
.constant("names", names)
.constant("friends", getFriends())
.controller("myController", MyController);
function getFriends() {
var friends = {};
names.forEach(function(name) {
friends[name] = { firstName: name };
});
return friends;
}
... however, I prefer to avoid this method (I prefer to have constants defined in separate JS files).
Note: The reason for not using a factory for friends
is to make both constants available during the configuration phase.