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 ?
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 ?
-
Can you avoid doing the foreach, and just do something like
<span data-bind="text: myArray()[0], visible: true"></span>
– Kal_Torak Commented Mar 2, 2013 at 8:15 - If myArray is an observable, don't forget you have to call it like a function to access the indices. Also, have you run it in Chrome and checked the console (f12)? What error is it giving you? – Kal_Torak Commented Mar 2, 2013 at 8:19
1 Answer
Reset to default 15You 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.