【问题标题】:How to get index item of array in emberjs view如何在emberjs视图中获取数组的索引项
【发布时间】:2012-07-16 10:16:13
【问题描述】:

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

这会返回一个错误:

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

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

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

{{#each oneArray}}
    {{#if index>0}}
         don't show the first item {{oneArray[index]}}
    {{/if}}
{{/each}} 

【问题讨论】:

  • {{#if}} 不能包含比较 afaik。它将检查一个虚假变量。即nullfalseundefined[]

标签: ember.js


【解决方案1】:

this article所示,你可以定义一个新的数组来包含每一行的索引:

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

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

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

但是,由于您只想显示数组中的特定项目,因此最好在您的视图中执行此操作(甚至在您的控制器中更好)。 尽量让你的模板没有逻辑

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

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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-28
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多