Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout.js using $index with if binding

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 -->
like image 709
user1255162 Avatar asked Jul 03 '12 20:07

user1255162


People also ask

For what purpose do we use foreach binding in Ko?

Purpose. The foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.

What is data bind knockout?

Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding.


2 Answers

$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 -->
like image 56
John Earles Avatar answered Oct 07 '22 17:10

John Earles


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
like image 25
JackMorrissey Avatar answered Oct 07 '22 15:10

JackMorrissey