Rolando
Rolando

Reputation: 762

Binding on select html control using knockout

I am working using breeze + knockout using as base hottowel template. Using this template I am able to make some binding like:

 <select data-bind="options: $parent.rolesList, value: role">

Where rolelist it's a ko.observableArray() and role it's a string property. everything it's fine with this example.

My issue begin when I try make some more complex databinding, i.e:

select data-bind="options: mycollection, optionsText: 'dictionary().name()'"></select>

In this new example mycollection it's ko.observableArray() and dictionary().name() it's "object property" plus a string property. If I go to chrome debuger I can see that mycollection()[0].dictionary().name() has a value.

So I dont' know what I am doing wrong. Here you are a short example( you can see that I am using just dictionary.name) http://jsfiddle.net/rolandomartinezg/BN2ZP/2/

Upvotes: 0

Views: 473

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

When passing a string to optionsText, Knockout simply tries to key into your object. It does not handle nested keys or run the string as JavaScript.

However, you can instead choose to pass a function for optionsText which takes in the item as the first argument and you can return whatever value that you like.

For example, in your jsFiddle, you could define a function like:

self.getOptionText = function(item) {
   return item.dictionary.name;   
};

Then, bind against it like:

<select data-bind="options: myCollection, optionsText: getOptionText"></select>

In your sample from the question, then you would just do item.dictionary().name() if you are dealing with observables.

Upvotes: 1

Related Questions