2012-07-16 62 views
3

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

这将返回一个错误:

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

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

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

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

'{{#如果}}'不能包含一个比较AFAIK。它会检查一个虚拟变量。即'null','false','undefined'或'[]'。 – albertjan 2012-07-17 07:58:32

回答

10

this article所示,您可以定义一个新的阵列,包括各行索引:

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

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

{{#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('[email protected]') 
相关问题