Angularjs 在同一角度模块中重用常量

Angularjs 在同一角度模块中重用常量,angularjs,Angularjs,我已经创建了自定义枚举(请参见代码),我希望重用声明为FOO和BAR的常量,而无需在类型数组中再次写入常量值。我该怎么做呢 var myApp = angular.module('app'); myApp.constant('MyEnum', { FOO: "foo", BAR: "bar", types: [ {id: 0, value: 'foo', label:"Foo"}, {id: 1, value: 'bar', label:"Bar"} ] }); 我想在类型数

我已经创建了自定义枚举(请参见代码),我希望重用声明为
FOO
BAR
的常量,而无需在
类型
数组中再次写入常量值。我该怎么做呢

var myApp = angular.module('app');
myApp.constant('MyEnum', {
FOO: "foo",
BAR: "bar",

types: [
    {id: 0, value: 'foo', label:"Foo"},
    {id: 1, value: 'bar', label:"Bar"}
]
});
我想在
类型
数组中执行类似操作:

types: [
    {id: 0, value: this.FOO, label:"Foo"},
    {id: 1, value: this.BAR, label:"Bar"}
]

但这样做会让我犯错误。有什么建议吗?

您必须为此使用中间变量。也许可以将它们存储在闭包中,这样就不会用不需要的变量污染作用域。例如:

var myApp = angular.module('app');
myApp.constant('MyEnum', function() {

   var __FOO = "foo",
       __BAR = "bar";

    return {

        FOO: __FOO,
        BAR: __BAR,

        types: [
            {id: 0, value: __FOO, label: "Foo"}, 
            {id: 1, value: __BAR, label: "Bar"}
        ]
    }
}());

谢谢在中间变量中使用两个下划线是否常见?@John它们通常表示“私有”变量。