I have the following models:
var allCategories = [{
id: 1,
name: 'Red'},
{
id: 5,
name: 'Blue'}];
function model() {
self = this;
self.name = ko.observable("");
self.categoryId = ko.observable(-1);
self.categoryName = ko.computed(function() {
if (self.categoryId() == -1) return "";
return getCategoryNameById(self.categoryId()).name;
});
}
function getCategoryNameById(id) {
return _.find(allCategories, function(cat) {
return cat.id == id;
});
}
I want to offer a dropdown to select the category but I have no clue how to bind that.
Maybe I’ve used the wrong approach with my models but that’s most likely how I get my data from the server so I’ve tried to wrap my JS around that.
I tried something like this:
<select data-bind="options: categories, optionsText: 'name', value: 'id', optionsCaption: 'Categorie...'"></select>
But I don’t get how to connect the dropdown value to the model categoryId.
Here is a fiddle with a working binding for the name property.
For your list box you need to specify:
options,optionsText,optionsValue, andvalue.value(which is the currently selected value) should point to yourmodel.categoryId(). AndoptionsValueis the property name where to get values for the list:And that’s it. And the working fiddle: http://jsfiddle.net/Y7Nrc/