Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout bind a key value object to dropdown

Tags:

knockout.js

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.

like image 636
kannix Avatar asked Nov 27 '12 15:11

kannix


People also ask

How do I assign a value to knockout observable?

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.

What is binding in knockout?

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>

What is two way binding in knockout JS?

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.


1 Answers

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/

like image 134
Max Shmelev Avatar answered Sep 19 '22 14:09

Max Shmelev