newman
newman

Reputation: 6911

JavaScript/Angular: How to initialize a property from an array of the same object?

This is what I'd like to do in an Angular factory:

app.factory('dataService', function () {
    return {
        data: ['5', '10', '20', '50', '100', '200'],
        selectedData: data[0],
        },
    },
)

Basically, I want to initialize selectedData to one of the items of predefiend data array. This code returns data is not defined. If I use this.data[0], I get the error: Cannot read property '0' of undefined. So, how do I refer to data here?

Upvotes: 0

Views: 301

Answers (2)

Seth Holladay
Seth Holladay

Reputation: 9539

That's not how this works.

If you really are sure that you want an object that has final values, then the answer from Troels Larsen is the way to go. However, in many applications, its wise to have objects that can get updated data for you at any time. It is difficult to show-and-tell without knowing your app, but doing that would look something like this...

app.factory('dataService', function () {
    var result = {
        data: ['5', '10', '20', '50', '100', '200'],
        getSelectedData: function (index) {
            return this.data[index];
        }
    }

    return result;
})

Then anywhere else, you can get access to exactly what you want - which is especially useful in situations where that data array may not be stable.

Upvotes: 0

Troels Larsen
Troels Larsen

Reputation: 4631

Try storing the object locally, then setting the value, and finally returning:

app.factory('dataService', function () {
    var obj = { data: ['5', '10', '20', '50', '100', '200'] };
    obj.selectedData = obj.data[0];
    return obj;
    }
)

You cannot reference data as you are defining the object.

Upvotes: 1

Related Questions