admin管理员组文章数量:1356946
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.
本文标签: javascriptgetting first element of array in knockout jsStack Overflow
版权声明:本文标题:javascript - getting first element of array in knockout js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744034810a2579570.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论