Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index item of array in emberjs view

Tags:

ember.js

How to get index item of array in an emberjs view.

This returns an error:

{{#view}}
  {{oneArray[0]}}
{{/view}}

I don't want to use {{#each}} to show all items, just want to show the special index item. How?

Or can I get the index of {{#each}}?

{{#each oneArray}}
    {{#if index>0}}
         don't show the first item {{oneArray[index]}}
    {{/if}}
{{/each}} 
like image 374
wind13 Avatar asked Dec 06 '25 18:12

wind13


1 Answers

As shown in this article, you can define a new array for including the index in each row:

App.MyView = Ember.View.extend({
    oneArrayWithIndices: function() {
      return this.get('oneArray').map(function(item, index) {
        return {item: i, index: idx};
      });
    }.property('oneArray.@each')
});

and then in your template you can access the index like so:

{{#each view.oneArrayWithIndices}}
  index: {{this.index}} <br />   
  item: {{this.item}}
{{/#each}}

However, since you just want to show specific items from the array, it is better to do it in your view (or even better in your controller). Try to keep your templates logic-less.

Therefore, create a new array in your view/controller that includes only the items you want to show:

myFilteredArray: function() {
  return this.get('oneArray').filter( function(item, index) {
    // return true if you want to include this item
    // for example, with the code below we include all but the first item
    if (index > 0) { 
      return true;     
    }    
  });
}.property('oneArray.@each')
like image 113
Panagiotis Panagi Avatar answered Dec 08 '25 09:12

Panagiotis Panagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!