Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positional index in Ember.js collections iteration

Is there a way to get positional index during iteration in ember.js?

{{#each itemsArray}}
     {{name}}
{{/each}}

I'm looking for a way to have something like:

{{#each itemsArray}}
    {{name}} - {{index}}th place.
{{/each}}

Update:

As per the comment by @ebryn the below code works without using a nested view for each item:

<script type="text/x-handlebars">    
    {{#collection contentBinding="App.peopleController"}}
        Index {{contentIndex}}: {{content.name}} <br />
    {{/collection}}
</script>​

http://jsfiddle.net/WSwna/14/

Although to have something like adjustedIndex, a nested view would be required.

like image 736
Gubbi Avatar asked Jan 15 '12 15:01

Gubbi


3 Answers

It's old question but still gets a lot of hits. In the current version of Ember.JS one can use _view.contentIndex to display current index inside the loop.

{{#each}}
    Index: {{_view.contentIndex}}
{{/each}}

If you need an adjusted index (for instance starting from 1) then there is a possibility of creating reusable helper increment

Ember.Handlebars.registerBoundHelper('increment', function(integer) {
    return integer + 1;
});

then you would use it in the following way

{{#each}}
    Index: {{increment _view.contentIndex}}
{{/each}}

Update

Starting with ember 1.11 you can do as well

{{#each people as |person index|}}
   Index: {{increment index}}
{{/each}}
like image 82
Mateusz Nowak Avatar answered Oct 24 '22 00:10

Mateusz Nowak


In RC6 CollectionView provides contentIndex propery for each rendered view of collection. Each helper uses CollectionView in its implementation so uou can access index in this way:

{{#each itemsArray}}
    {{_view.contentIndex}}
{{/each}}
like image 21
chrmod Avatar answered Oct 24 '22 00:10

chrmod


Actually yes you can get the position of the current index using the {{each}} helper. You have to create a view for every item in a list and then use {{_parentView.contentIndex}}.

<script type="text/x-handlebars">
{{#each App.peopleController}}
  {{#view App.PersonView contentBinding="this"}}
    Index {{_parentView.contentIndex}}: {{content.name}} {{adjustedIndex}} <br />
  {{/view}}
{{/each}}
</script>

App = Ember.Application.create();

App.peopleController = Ember.ArrayController.create({
  content: [ { name: 'Roy' }, { name: 'Mike' }, { name: 'Lucy' } ]
});

App.PersonView = Ember.View.extend(Ember.Metamorph, {
  content: null,
  // Just to show you can get the current index here too...
  adjustedIndex: function() {
    return this.getPath('_parentView.contentIndex') + 1;
  }.property()
});

See this jsFiddle for a working example.

like image 9
Roy Daniels Avatar answered Oct 23 '22 22:10

Roy Daniels