最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - getting first element of array in knockout js - Stack Overflow

programmeradmin0浏览0评论

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

Uncaught TypeError: Unable to process binding "text: function (){return Items[0].name }" Message: Cannot read property 'name' of undefined

Share Improve this question asked Dec 8, 2015 at 9:39 Vignesh SubramanianVignesh Subramanian 7,30914 gold badges96 silver badges158 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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>
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.

发布评论

评论列表(0)

  1. 暂无评论