0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

This won't actually return the object he wants (I assume), but just '5'. He wants the collection AND the currently selected value.
Indeed, I had meant to show how you might use the object to get the value. But it was about the worst way possible to do that. Edited to properly explain my intended message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.