我可以用角度定义一个常量吗,它本身取决于传递给它的常量吗? Here's a contrived example:在Angular中,我可以将常量传递给常量吗?
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
的原因是因为我想在配置阶段提供这两个常量。
有趣的方法...虽然感觉就像它违反了什么是恒定的意思! – gerrod