I’ve recreated the problem in the following jsfiddle:
HTML
<h2>Edit Person Here</h2>
<div data-bind="with: EditPerson">
<h3 data-bind="html: Name"></h3>
<!--Uncomment line below to generate binding error. -->
<!--<select data-bind="options:$parent.IceCreams, optionsText: Name, optionsValue: Id"></select>-->
</div>
<h2>List of People</h2>
<div data-bind="foreach: People">
<div data-bind="click: $parent.SelectPerson">
<h3 data-bind="html: Name"></h3>
Favorite IceCream: <span data-bind="html: FavoriteIceCream().Name"></span>
</div>
</div>
Javascript
function ViewModel() {
var self = this;
self.IceCreams = ko.observableArray([
new IceCream(1, "Chocolate"),
new IceCream(2, "Vanilla"),
new IceCream(3, "Mint")
]);
self.EditPerson = ko.observable(new Person("", self.IceCreams()[0]));
self.People = ko.observableArray([
new Person("Joe", self.IceCreams()[2]),
new Person("Sue", self.IceCreams()[0]),
new Person("Carl", self.IceCreams()[1])
]);
self.SelectPerson = function(person){
self.EditPerson(person);
}
}
function Person(Name, FavoriteIceCream){
var self = this;
self.Name = ko.observable(Name);
self.FavoriteIceCream = ko.observable(FavoriteIceCream);
}
function IceCream(Id, Name){
var self = this;
self.Id = Id;
self.Name = Name;
}
ko.applyBindings(new ViewModel());
When you select a person from the list, their name will appear above. I want to add a dropdown that allows you to choose the selected person’s favorite icecream. I have what I would expect to work commented out in the html.
However, it appears that instead of taking the context of the options parameter objects, it’s using the context of the with parameter of the parent div.
How can I write the select tag so that the binding works?
optionsTextandoptionsValueneed to be either strings or functions. See the options documentation for more information.Example: http://jsfiddle.net/mbest/DhgRL/3/