5

I'm bit new and confused about Ember iterations.

I'm trying to construct a select inside ember template, like:

<select id="state_list">
  {{#each stateArrays as |stateArray|}}
    <option value={{stateArray[0]}}>{{stateArray[1]}}</option>
  {{/each}}
</select>

Here, stateArrays looks like:

[[1, "Alabama"], [2, "Alaska"], [3, "Arizona"]]

But, this throws error. When I try {{stateArray}}, I get string like "1, Albama"...

How to achieve the above in single iteration?

2 Answers 2

2

Not that I love this technique, but you can access the individual elements on an array like this

{{#each stateArrays as |stateArray|}}
    <option value={{stateArray.[0]}}>{{stateArray.[1]}}</option>
  {{/each}}

Twiddle

Saves you having to write extra code.

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

2 Comments

I was thinking the same thing about this functionality. It really feels weird to use, but is the most straightforward technique to access an array specific element without adding any code to an Ember application. I couldn't find any example of this on Ember website, but do you know of any official reference about it?
No, I can't sorry. Had a quick look, but couldn't see anything in the docs. Plenty of reference to it in official channels like Github issues though, but only in passing.
1

You can convert the array of arrays into an array of objects:

mappedArray = [[1, "Alabama"], [2, "Alaska"], [3, "Arizona"]].map(function(array){
    return { num: array[0] , str: array[1] };
})

Then you can use it as:

<select id="state_list">
    {{#each mappedArray as |obj|}}
        <option value={{obj.num}}>{{obj.str}}</option>
    {{/each}}
</select>

Basically we cannot use syntax like stateArray[0] in the template.

UPDATE

If you don't want to create another array (mappedArray), you can write a helper:

App.GetArrayItemHelper = Ember.Helper.helper(function(values) {
    var array = values[0], index = values[1];
    return array[index];
})

Then in your template:

<select id="state_list">
    {{#each stateArrays as |stateArray|}}
        <option value={{get-array-item stateArray 0}}>{{get-array-item stateArray 1}}</option>
    {{/each}}
</select>

Comments

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.