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
1 Answer
Reset to default 9Since 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/