【发布时间】:2015-01-15 07:48:24
【问题描述】:
我可以在角度定义一个常数,它本身取决于传递给它的常数吗? Here's a contrived 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;
}
所以本质上,names 常量定义了一个名称数组,然后我将其传递给一个函数以生成一堆对象字面量。
这段代码肯定行不通 - 但是有没有办法可以完成这种想法?我唯一能想到的就是这样......
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;
}
...但我试图避免这种情况(我希望在单独的 JS 文件中定义常量)。
注意:我没有为friends 使用工厂的原因是我希望在配置阶段这两个常量都可用。
【问题讨论】:
标签: javascript angularjs constants