0
votes

I am unable to access the EmberArray by index in the template. This is part of my route

model(){
  return RSVP.hash({
    games: this.store.findAll('game')
  })
}

And this is part of the template

<div>
  First game: {{model.games.[0].name}}
</div>

There is no output that is rendered. Although if I iterate over it using

{{#each model.games as |game|}}
  <div>{{game.name}}</div>
{{/each}}

This works fine. Any idea what I might be doing wrong, or what I should do different ?

Thanks

3

3 Answers

2
votes

You can use firstObject method.

{{model.games.firstObject.name}}
2
votes

If you don't want to iterate over all of items and if you don't mind composing a bit of logic dierctly in the template, ember-composable-helpers addon might come useful, for example accessing a concrete item in a given array using object-at, from the docs:

Returns the object at the given index of an array.

Notation:

{{object-at index array}}

which (in a case you want to show a name of the second item) would be:

{{object-at 1 model.games}}

1
votes

You can create a helper. Something like this:

// app/helpers/array-index.js
import Ember from 'ember';

export default Ember.Helper.helper(function ([array, index]) {
  return array !== undefined && array[index] !== undefined ? array[index] : undefined;
});

Use it together with get:

{{get (array-index model.games 1) 'name'}}

P.S. As we are talking about collection returned from Ember Data, that's may be not a pure js array, but something like ArrayProxy. In this case you probably need to use it's method objectAt:

// app/helpers/array-index.js
import Ember from 'ember';

export default Ember.Helper.helper(function ([array, index]) {
  return array && array.objectAt ? array.objectAt(index) : (array && array[index]);
});