Ember.js 集合迭代中的位置索引 [英] Positional index in Ember.js collections iteration
问题描述
ember.js 有没有办法在迭代过程中获取位置索引?
Is there a way to get positional index during iteration in ember.js?
{{#each itemsArray}}
{{name}}
{{/each}}
我正在寻找一种方法来拥有类似的东西:
I'm looking for a way to have something like:
{{#each itemsArray}}
{{name}} - {{index}}th place.
{{/each}}
更新:
根据@ebryn 的评论,以下代码无需为每个项目使用嵌套视图即可工作:
As per the comment by @ebryn the below code works without using a nested view for each item:
<script type="text/x-handlebars">
{{#collection contentBinding="App.peopleController"}}
Index {{contentIndex}}: {{content.name}} <br />
{{/collection}}
</script>
虽然有一些类似adjustedIndex的东西,但是需要一个嵌套的视图.
Although to have something like adjustedIndex, a nested view would be required.
推荐答案
这是个老问题,但仍然有很多点击.在当前版本的 Ember.JS 中,可以使用 _view.contentIndex
在循环内显示当前索引.
It's old question but still gets a lot of hits. In the current version of Ember.JS one can use _view.contentIndex
to display current index inside the loop.
{{#each}}
Index: {{_view.contentIndex}}
{{/each}}
如果您需要调整索引(例如从 1 开始),则有可能创建可重用的助手 increment
If you need an adjusted index (for instance starting from 1) then there is a possibility of creating reusable helper increment
Ember.Handlebars.registerBoundHelper('increment', function(integer) {
return integer + 1;
});
那么你会以下面的方式使用它
then you would use it in the following way
{{#each}}
Index: {{increment _view.contentIndex}}
{{/each}}
更新
从 ember 1.11 开始,你也可以这样做
Starting with ember 1.11 you can do as well
{{#each people as |person index|}}
Index: {{increment index}}
{{/each}}
这篇关于Ember.js 集合迭代中的位置索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!