Getting $index of grand parent in a nested loop

£可爱£侵袭症+ 提交于 2020-01-21 10:39:15

问题


How to access the index of the grand parent in the nested loop?

For example:

<div class="loop" data-bind="foreach: rows">
    <div class="nested-loop" data-bind="foreach: cells">
        <div class ="nested-nested-loop" data-bind="foreach: candidates, css : {selected : $root.isSelected($parentContext.$parentContext.$index(), $parentContext.$index(), $index())}">
            Candidate index: <span data-bind="text: $index()"></span>
            Cell index: <span data-bind="text: $parentContext.$index()"></span>
            Row index: <span data-bind="text: $parentContext.$parentContext.$index()"></span>
        </div>
    </div>
</div>

I tried to bind like this:

css : {selected : $root.isSelected($parentContext.$parentContext.$index(), $parentContext.$index(), $index())}

and I encountered:

TypeError: $parentContext.$parentContext.$index is not a function


回答1:


If you want to display the index form the grand-parent you need the $parentContext of the $parentContext, so you need to write:

Row index: <span data-bind="text: $parentContext.$parentContext.$index()"></span>

http://jsfiddle.net/fjYsG/

It is not working in your css binding because you have the binding on the same element as your foreach so the binding context is not correctly set at their point.

You can solve this with moving the foearch and the css on different elements like using the containrless binding systax:

<div class="loop" data-bind="foreach: rows">
    <div class="nested-loop" data-bind="foreach: cells">
        <!-- ko foreach: candidates -->
            <div class="nested-nested-loop" 
                data-bind="css : {selected : 
                    $root.isSelected($parentContext.$parentContext.$index(), 
                    $parentContext.$index(), $index())}">
              Candidate index: <span data-bind="text: $index()"></span>
              Cell index: <span data-bind="text: $parentContext.$index()"></span>
              Row index:  <span 
                 data-bind="text: $parentContext.$parentContext.$index()"></span>

           </div>
        <!-- /ko -->
    </div>
</div>

Demo JSFiddle.



来源:https://stackoverflow.com/questions/20497540/getting-index-of-grand-parent-in-a-nested-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!