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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With