3

emberjsビューで配列のインデックスアイテムを取得する方法。

これはエラーを返します:

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

{{#each}}を使用してすべてのアイテムを表示するのではなく、特別なインデックスアイテムを表示したいだけです。どのように?

または、{{#each}}のインデックスを取得できますか?

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

1 に答える 1

10

この記事に示されているように、各行にインデックスを含めるための新しい配列を定義できます。

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')
于 2012-07-16T11:57:50.960 に答える