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.
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
A binding consists of two items, the binding name and value, separated by a colon. Here is an example of a single, simple binding: Today's message is: <span data-bind= "text: myMessage" ></span>
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
For your list box you need to specify: options
, optionsText
, optionsValue
, and value
.
value
(which is the currently selected value) should point to your model.categoryId()
. And optionsValue
is the property name where to get values for the list:
<select data-bind="options: categories, optionsText: 'name', optionsValue: 'id', value: $root.model.categoryId(), optionsCaption: 'Categorie...'"></select>
And that's it. And the working fiddle: http://jsfiddle.net/Y7Nrc/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With