如何在emberjs视图中获取数组的索引项 [英] How to get index item of array in emberjs view

查看:207
本文介绍了如何在emberjs视图中获取数组的索引项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



返回错误:

  {{view}} 
{{oneArray [0]}}
{{/ view}}
pre>

我不想使用{{#each}}显示所有项目,只想显示特殊的索引项。如何?



或者可以获取{{#each}}的索引?

 code> {{#each oneArray}} 
{{#if index> 0}}
不显示第一个项{{oneArray [index]}}
{ / if}}
{{/ each}}


解决方案

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

  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){
//如果你想要的话返回true要包括这个项目
//例如,下面的代码包括除第一个项目之外的所有项目
if(index> 0){
return true;
}
});
} .property('oneArray。@ each')


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}} 

解决方案

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

这篇关于如何在emberjs视图中获取数组的索引项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆