0

How to get $index of second foreach inside innermost foreach if we are having 3 nested foreach? $index gives us counter of innermost foreach and $parentContext gives us counter of outermost foreach. What about the middle foreach?

  • The parent context should work for this - can you show an example of where it's not working for you? – James Thorpe Feb 22 '17 at 14:39
  • Besides hitting up `parent` which should work for you, consider using `as` in the foreach binding to give your element an alias like `foreach: { data: people, as: 'person' }`. Inner foreach's can reference parent elements by name making everything much cleaner to read as you get deeply nested. There's a great example of this on the [knockout foreach page](http://knockoutjs.com/documentation/foreach-binding.html) about half way down. – JNevill Feb 22 '17 at 14:49

1 Answers1

1

You can move up the $parentContext as many times as you like. So: $index() > $parentContext.$index() > $parentContext.$parentContext.$index()...

The example below shows that

  1. it works, and
  2. it's ugly and prone to error...

A better solution is to include a (computed) index property in your actual items.

ko.applyBindings({
  items: [{
      items: [{
          items: [1, 2, 3]
        },
        {
          items: [4, 5, 6]
        }
      ]
    },
    {
      items: [{
        items: [7, 8, 9],
      }, {
        items: [0, 1]
      }]
    }
  ]
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach: items">
  <li>
    <strong data-bind="text: $index()"></strong>
    <ul data-bind="foreach: items">
      <li>
        <strong data-bind="text: [
          $parentContext.$index(),
          $index()].join('.')"></strong>
        <ul data-bind="foreach: items">
          <li>
            <strong data-bind="text: [
              $parentContext.$parentContext.$index(),
              $parentContext.$index(),
              $index()].join('.')"></strong>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
user3297291
  • 22,592
  • 4
  • 29
  • 45
  • $parentContext.$parentContxt.$index() worked for me. Thanks a lot. I thought $parentContext gives you the outermost foreach context which is wrong. It gives you the context of just one step outer foreach. –  Feb 23 '17 at 07:16