在emberjs中访问#each中的索引

50
请查看附加的代码:

http://jsbin.com/atuBaXE/2/

我试图使用{{@index}}访问索引,但似乎无法编译。我认为handlebars支持这个功能:

{{#each item in model}}
  {{@index}} 
  {{item}}
{{/each}}

对我来说它不能工作。 我无法确定是否支持{{@index}}

我正在使用:

  • Ember.VERSION:1.0.0
  • Handlebars.VERSION:1.0.0

跟踪:https://github.com/toranb/ember-template-compiler/issues/16 - givanse
5个回答

139

更新

自从这个 PR 后,现在可以使用带有索引的 each helper,并且可以利用新的 block params 语法。这在 canary 上可用,希望会默认启用在 ember 1.11 中。

{{#each model as |item index|}}
  <li>
    Index: {{index}} Content: {{item}}
  </li>
{{/each}}

实时演示

对于旧版本:

您可以使用{{_view.contentIndex}}

{{#each item in model}}
  <li>
    Index: {{_view.contentIndex}} Content: {{item}}
  </li>
{{/each}}

实时示例


5
有没有一种方法可以获取从1开始的索引值?例如,第一个项目应返回1(而不是0),最后一个项目应返回n(而不是n-1),其中n为具有n个项目的数组。 - ioleo
1
我认为唯一的方法是使用索引将模型包装在计算属性中,就像这样http://emberjs.jsbin.com/xeboqegu/1/edit - Marcio Junior
如果每个块中的项目被更新,例如通过更改它们的排序顺序,则对于所有项目,_view.contentIndex都不会更新,这可能导致索引值不正确。 - TrevTheDev
emblem 支持块语法吗?= each model as |item index|对我不起作用。 - ahnbizcad
@loostro 我创建了一个帮助程序,它简单地递增传入的数字以获取基于1的索引:http://pastebin.com/jphC3Xnh - MichaelM

4

在Ember的Handlebars版本中,它不存在。一种方法是使用item controller并向其添加一个属性,表示它是否为第一个或最后一个等。

App.IndexController = Ember.ArrayController.extend({
  itemController: 'itemer'
});

App.ItemerController = Ember.ObjectController.extend({
  needs:['index'],
  isFirst: function(){
    return this.get('color') === this.get('controllers.index.firstObject.color');
  }.property('controllers.index.firstObject')
});

http://emberjs.jsbin.com/aPewofu/1/edit


我认为你写的东西真的很棒,我相信任何人都会从中受益。 - Mohammad Abu Musa
这两个控制器之间过于紧密地耦合会有危险吗? - end-user
不是危险,而是缺乏可重用性。这完全取决于使用情况。 - Kingpin2k

3

2

我喜欢@kingpin2k的答案--Ember的方式是使用控制器来装饰模型,在这种情况下,我们想通过添加索引属性来装饰它,以表示其在集合中的位置。

我有些不同的做法,通过构建一个单独的实例控制器集合来完成所需任务的装饰:

App.PostsIndexController = Ember.ArrayController.extend({
  indexedContent: function() {
    get('content').map(function(item, index) {
      App.PostsItemController.create({
        content: item,
        index: index
      });
    });
  }.property('content')
});

App.PostsItemController = Ember.ObjectController.extend({
  index: null
});

1

如果你只是想在视图中显示索引作为从1开始的值,也可以尝试使用CSS计数器。它们从IE 8开始就被支持了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接