Reputation: 7289
I am populating an array of objects in knockoutjs
I wanted to avoid the use of foreach, so I tried to data-bind
the first item
if i use the below code it is working fine
<div class="loader" data-bind="foreach: Items" >
<span data-bind="text: name"></span>
</div>
But if i use, the one below, its not working
<div class="loader">
<span data-bind="text: Items[0].name"></span>
</div>
What is the mistake in the second way?
The error I am getting is
Uncaught TypeError: Unable to process binding "text: function (){return Items[0].name }" Message: Cannot read property 'name' of undefined
Upvotes: 2
Views: 8636
Reputation: 1497
Use either Items()[0].name
or ko.unwrap(Items)[0]
I would recommend the second one since it is safer because it would return the array even if Items is not an observable array, hence helps avoiding exceptions.
Upvotes: 1
Reputation: 6045
well you need to unwrap
the observableArray Items
to read it's content using ()
notation .
Try like this
<div class="loader">
<span data-bind="text: Items()[0].name"></span>
</div>
Upvotes: 4