Asked By: Anonymous
I followed http://mozmonkey.com/2014/03/ember-getting-the-index-in-each-loops/ blog post to add index counter through helper. This works perfectly fine with single each loop. But when i use it with nested each loop the value gets repeated. Example :
{{#each item in data}}
{{#eachIndexed record in item.innerdata}}
{{index_1}}
{{/eachIndexed}}
{{/each}}
I have two objects in data and two objects in each innerdata. Expected result is
1 2 3 4
but I’m getting
1 2 1 2
How do i get the expected result? My handlebars version is 1.1.2 and ember version is 1.6.1.
Solution
Answered By: Anonymous
If your data is:
[
{innerdata: ['foo', 'bar']},
{innerdata: ['foo', 'bar']}
]
Then it’s working as intended because it’s an index not a counter.
{{#each item in data}}
Outer Index: {{index_1}}<br>
{{#eachIndexed record in item.innerdata}}
Inner Index: {{index_1}}<br>
{{/eachIndexed}}
{{/each}}
Would output:
Outer Index: 1
Inner Index: 1
Inner Index: 2
Outer Index: 2
Inner Index: 1
Inner Index: 2
If you want to count the number of iterations, you could try this answer: https://stackoverflow.com/a/15376389/29347
(function() {
var positionCounter = 1;
Handlebars.registerHelper('position', function() {
return positionCounter++;
});
})();
Which gives you:
{{#each item in data}}
{{#eachIndexed record in item.innerdata}}
{{position}}
{{/eachIndexed}}
{{/each}}