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.
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}}
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}}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With