How to show only the first element in a foreach loop binding?

I am using knockout-2.2.0.js. I created a foreach loop binding for an observable array, and I want to show only the first element in the array. For this, I tried: (both do not work)

First

<!-- ko foreach: myArray --> <span data-bind="text: $data, visible: $index == 0"></span> <!-- /ko --> 

Second

  <span data-bind="text: myArray[0]"></span> 

I know that there is a _destroy property, which, if set to any element in the array than this element, will be excluded from the foreach loop binding in the user interface. But I do not want to use this in my case. Can someone please tell me what I'm doing wrong here?

+6
source share
1 answer

You are on the right track. But you forgot to output () in both of your examples.

myArray is an observable array and $index is observable, so they are functions, so you need to call them as functions using () to get their values ​​inside the expressions.

So the correct bindings are:

 <!-- ko foreach: myArray --> <span data-bind="text: $data, visible: $index() == 0"></span> <!-- /ko --> 

and

 <span data-bind="text: myArray()[0]"></span> 

JSFiddle demo.

Note. If you really want to display the first element, you should prefer the text: myArray()[0] version, because what you are trying to do is much cleaner there.

+15
source

All Articles