1

I have made my custom enum (see code), and I would like to reuse the constants declared as FOO and BAR without having to write the value of the constants again in the types array. How would I go about doing that?

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"}
]
});

I would like to do something like this in the types array:

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

but doing it like this gives me errors. Any suggestions?

1 Answer 1

2

You will have to use intermediate variables for this. Maybe to store them in the closure so you don't pollute scope with unneeded variables. For example:

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"}
        ]
    }
}());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! is it common to use two underscores in the intermediate variables?
@John They generally means "private" variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.