最佳答案
在 linkout.js 2.1.0中,在使用 foreach 绑定的模板中,可以通过 $index ()函数访问当前项的索引。在嵌套 foreach 绑定中,是否有办法从模板访问 $father 的索引?
假设我有一个这样的数据结构:
var application = {
topModel: [
{
{subModel: [{'foo':'foo'}, { 'bar':'bar'}]}, // this has top:0 and sub:0
{subModel: [{'foo2':'foo2'}, { 'bar2':'bar2'}]} // this has top:0 and sub:1
},
{
{subModel: [{'foo':'foo'}, { 'bar':'bar'}]} // this is top:1 sub:0
},
{
{subModel: [{'foo':'foo'}, { 'bar':'bar'}]} // this is top:2 sub:0
{subModel: [{'foo':'foo'}, { 'bar':'bar'}]} // this is top:2 sub:1
},
...
]};
通过这个,我想打印每个模型的路径,使用索引: [ topModel-index subModel-index ] ,因此输出类似于:
[0 0]
[0 1]
[1 0]
[2 0]
[2 1]
...
我已经使用 foreach 绑定了模型,但是我不知道如何在子模型的上下文中访问 topModel 的索引。下面的示例显示了一种我尝试过的方法,但是它不起作用,因为我不知道如何访问 $father 引用程序的索引。
<!--ko foreach: topModel -->
<!--ko foreach: subModel -->
[<span data-bind="text: $parent.index()"></span>
<span data-bind="text: $index()"></span>]
<!--/ko-->
<!--/ko-->
打印出来: 01,02,10,11,12,20,21..。