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

javascript - KnockoutJS binding first element in an array to a div - Stack Overflow

programmeradmin4浏览0评论

Jsfiddle

I am trying to bind the first element of an array to a div but it is failing miserably. Why will john not show up in the div?

<div data-bind="text: seedData[0].firstName"></div>
<select data-bind="options: seedData,
                        optionsText: 'firstName',
                        optionsValue: 'ID',
                        value: data.selectedValue">
</select>

var vm = {

    // Simulated seed data from server
    seedData: ko.observableArray([
    {
        ID: 1,
        firstName: 'John',
        value: '333'
    },
    {
        ID: 2,
        firstName: 'Bob',
        value: '333'
    },
    {
        ID: 3,
        firstName: 'Amy',
        value: '333'
    }]),

    // Simulated data from server
    data: {
        title: ko.observable('This is a sample'),
        selectedValue: ko.observable(2)
    }
};
ko.applyBindings(vm);

Jsfiddle

I am trying to bind the first element of an array to a div but it is failing miserably. Why will john not show up in the div?

<div data-bind="text: seedData[0].firstName"></div>
<select data-bind="options: seedData,
                        optionsText: 'firstName',
                        optionsValue: 'ID',
                        value: data.selectedValue">
</select>

var vm = {

    // Simulated seed data from server
    seedData: ko.observableArray([
    {
        ID: 1,
        firstName: 'John',
        value: '333'
    },
    {
        ID: 2,
        firstName: 'Bob',
        value: '333'
    },
    {
        ID: 3,
        firstName: 'Amy',
        value: '333'
    }]),

    // Simulated data from server
    data: {
        title: ko.observable('This is a sample'),
        selectedValue: ko.observable(2)
    }
};
ko.applyBindings(vm);
Share edited Jan 20, 2014 at 21:43 Captain John 2,0012 gold badges19 silver badges32 bronze badges asked Jan 20, 2014 at 21:36 gh9gh9 10.7k11 gold badges65 silver badges96 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Since you are accessing the value of the observable, you have to remember that it is a function. When binding to an observable (and not its subproperties) you can leave off the function and Knockout will do it for you. But when accessing the index, you have to use the function.

So use:

<div data-bind="text: seedData()[0].firstName"></div>
<select data-bind="options: seedData,
                        optionsText: 'firstName',
                        optionsValue: 'ID',
                        value: data.selectedValue">
    </select>

http://jsfiddle/VLTFB/386/

发布评论

评论列表(0)

  1. 暂无评论