How do I use KnockoutJS to bind a dictionary collection to a select list.
If my "Destinations" dictionary looks like this in JSON:
{"Europe":"Europe incl Egypt, Turkey & Tunisia","ANZO":"Australia & New Zealand","WorldwideUSA":"Worldwide (incl USA & Canada)"}
How do I bind this to a select list. Something like this:
data_bind="value: Destination, options: Destinations.Value, optionsText: Destinations.Key"
Text binding causes the associated DOM element to display the text value of the parameter. This is used in text-level DOM elements such as <span> or <em>. The text binding accepts any data type and parses it into String before rendering it.
To read the observable's current value, just call the observable with no parameters. In this example, myViewModel. personName() will return 'Bob' , and myViewModel. personAge() will return 123 .
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.
The value binding links the associated DOM element's value with a property on your view model. This is typically useful with form elements such as <input> , <select> and <textarea> . When the user edits the value in the associated form control, it updates the value on your view model.
Typically, when dealing with a dictionary, you will want to map it to an array containing objects with key/value properties.
Would be something like:
function mapDictionaryToArray(dictionary) {
var result = [];
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
result.push({ key: key, value: dictionary[key] });
}
}
return result;
}
Sample here: http://jsfiddle.net/rniemeyer/7yDTJ/
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