2015-01-15 118 views
2

我可以用角度定义一个常量吗,它本身取决于传递给它的常量吗? 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的原因是因为我想在配置阶段提供这两个常量。

回答

0

看起来答案是公司 - 您无法将常数传递给常量。

我结束了using a provider instead

angular 
    .module("myApp", []) 
    .constant("names", ["Bob", "Jane"]) 
    .provider("friends", FriendsProvider); 

FriendsProvider.$inject = ["names"]; 

function FriendsProvider(names) { 
    var self = this; 
    self.friends = {}; 

    // ----- 8< ----- 

    self.$get = [function() { 
     return self.friends; 
    }];  
} 
0

你可以在模块的config阶段做一些处理,where constants are available

angular.module('myModule').constant('names', ['Bob', 'Jane']); 
angular.module('myModule').constant('friends', {}); 

angular.module('myModule').config(function(names, friends) { 
    names.forEach(function(name) { 
    // Modifying the friends constant 
    friends[name] = { firstName: name }; 
    }); 
}); 

请注意,当你不能改变什么反对不变指的是,你可以改变物体本身。

+0

有趣的方法...虽然感觉就像它违反了什么是恒定的意思! – gerrod

相关问题