Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using knockout-2.2.0.js. I have created a foreach loop binding on observableArray and i want to show only first element in the array. For this i tried : (both 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 on any array element than that element will be excluded from the foreach loop binding in UI. But i dont want to use this in my case. Can anybody please tell me what i am doing wrong here ?

like image 217
user1740381 Avatar asked Mar 02 '13 08:03

user1740381


People also ask

How do you get the first value in forEach?

Method 3: The reset() function is used to find the first iteration in foreach loop. When there is no next element is available in an array then it will be the last iteration and it is calculated by next() function.

Can forEach return a value?

forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

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.


1 Answers

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

myArray an observable array and $index is an observable so they are functions so you need to call them as functions with () to get their values inside 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>  

Demo JSFiddle.

Note: if you really just want to display the first item then you should prefer the text: myArray()[0] version because it is much cleaner there what you are trying to do.

like image 140
nemesv Avatar answered Nov 14 '22 22:11

nemesv