如何在emberjs视图中获取数组的索引项

win*_*d13 3 ember.js

如何在emberjs视图中获取数组的索引项.

这会返回一个错误:

{{#view}}
  {{oneArray[0]}}
{{/view}}
Run Code Online (Sandbox Code Playgroud)

我不想使用{{#each}}来显示所有项目,只是想显示特殊索引项目.怎么样?

或者我可以获得{{#each}}的索引吗?

{{#each oneArray}}
    {{#if index>0}}
         don't show the first item {{oneArray[index]}}
    {{/if}}
{{/each}} 
Run Code Online (Sandbox Code Playgroud)

Pan*_*agi 10

本文所示,您可以定义一个新数组,以在每行中包含索引:

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

然后在您的模板中,您可以像这样访问索引:

{{#each view.oneArrayWithIndices}}
  index: {{this.index}} <br />   
  item: {{this.item}}
{{/#each}}
Run Code Online (Sandbox Code Playgroud)

但是,由于您只想显示数组中的特定项目,因此最好在视图中执行此操作(或者在控制器中更好).尽量保持模板逻辑更少.

因此,在视图/控制器中创建一个仅包含要显示的项目的新数组:

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')
Run Code Online (Sandbox Code Playgroud)