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 ?
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.
forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With