I am trying to display an observable array in a dropdown, and when the user selects the option, I want to present a property of that view model. It seems simple. I have provided code and a link to Fiddle.
HTML:
<select data-bind="options: oCountries,
optionsText: 'name',
optionsValue: 'isocode',
value: selectedCountry">
</select>
Controlled by <span data-bind="value: selectedCountry.isocode"></span>
JS:
var countries = [{
"name": "Afghanistan",
"isocode": "AF",
"language": 开发者_如何学运维"English",
"crmdatacontroller": "CRM India"
}, {
"name": "Aland Islands",
"isocode": "AX",
"language": "Finnish",
"crmdatacontroller": "CRM Finland"
}]
var viewModel = {
oCountries: ko.observableArray(countries),
selectedCountry: ko.observableArray(['AX'])
};
ko.applyBindings(viewModel);
See also this fiddle
The optionsValue
parameter controls what is written by the value
binding. So, in your case, it will write the isocode
to selectedCountry
.
So, the simplest changes to your code would be to set selectedCountry to a normal observable and the appropriate isocode. Then, have your span use the text
binding against selectedCountry
.
Like this: http://jsfiddle.net/wxNrt/21/
Now, a couple other options available to you as well:
-if you leave off optionsValue
in the binding, then it will set/read the object directly. In that case, you need to change how you are intially setting it.
http://jsfiddle.net/wxNrt/23/
-if you want to send/receive a key (like the isocode), then you can use optionsValue
, but set up a dependentObservable to represent the actual object like:
http://jsfiddle.net/wxNrt/22/
-if you are dealing with a multi-select situation, then you want to use the selectedOptions
binding instead of value
, as described here: http://knockoutjs.com/documentation/selectedOptions-binding.html
I changed your markup to this:
<select data-bind="options: oCountries, optionsText: 'name', optionsValue: 'isocode', value: selectedCountry">
</select>
Controlled by <span data-bind="text: selectedCountry"></span>
And the script:
var countries = [
{
"name": "Afghanistan",
"isocode": "AF",
"language": "English",
"crmdatacontroller": "CRM India"},
{
"name": "Aland Islands",
"isocode": "AX",
"language": "Finnish",
"crmdatacontroller": "CRM Finland"}
]
var viewModel = {
oCountries: ko.observableArray(countries),
selectedCountry: ko.observable('AX')
};
ko.applyBindings(viewModel);
And the jsfiddle
精彩评论