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
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
Share Improve this question asked Dec 8, 2015 at 9:39 Vignesh SubramanianVignesh Subramanian 7,30914 gold badges96 silver badges158 bronze badgesUncaught TypeError: Unable to process binding "text: function (){return Items[0].name }" Message: Cannot read property 'name' of undefined
3 Answers
Reset to default 4well 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>
text: Items()[0].name
Check it.
Use either Items()[0].name
or ko.unwrap(Items)[0]
I would remend 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.