3

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}} 
1
  • {{#if}} can not contain a comparison afaik. it will check for a falsy variable. i.e. null, false, undefined or []. Commented Jul 17, 2012 at 7:58

1 Answer 1

10

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.