knockout.js using $index with if binding

Javascriptknockout.js

Javascript Problem Overview


I'm trying to show some mark up based on the value of $index, I can display the value but I can't seem to use it with an if binding, what's the best approach here?

<!-- ko if: $index===0 -->
  <div>some mark up here</div>
<!-- /ko -->

Javascript Solutions


Solution 1 - Javascript

$index is an observable, and observables are functions. When you use observables in an expression you must use the () form to access the value.

<!-- ko if: $index() === 0 -->

Solution 2 - Javascript

From the knockout bindings page

> $index (only available within foreach bindings) > > This is the zero-based index of the current array entry being rendered > by a foreach binding. Unlike the other binding context properties, > $index is an observable and is updated whenever the index of the item > changes (e.g., if items are added to or removed from the array).

Example

<div data-bind="foreach: details.additionalDetails">
    <!-- ko if: $index() !== 0 -->
        <span> | </span>
     <!-- /ko -->
        <span data-bind="text: name"></span> <span data-bind="text: value"></span>
</div>

Results in

Model #: UAI5021 | Catalog #: UIOY786

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1255162View Question on Stackoverflow
Solution 1 - JavascriptJohn EarlesView Answer on Stackoverflow
Solution 2 - JavascriptJackMorrisseyView Answer on Stackoverflow