Reputation: 10703
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);
Upvotes: 3
Views: 3990
Reputation: 1297
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.net/VLTFB/386/
Upvotes: 9