使用下拉列表时将文本值绑定到视图模型的另一个属性

Bra*_*yer 2 javascript knockout.js

我试图在下拉列表中显示一个可观察的数组,当用户选择该选项时,我想呈现该视图模型的属性.看起来很简单.我提供了代码和Fiddle的链接.

HTML:

<select data-bind="options: oCountries, 
                   optionsText: 'name', 
                   optionsValue: 'isocode', 
                   value: selectedCountry">
</select>

Controlled by <span data-bind="value: selectedCountry.isocode"></span>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

另见这个小提琴

RP *_*yer 5

optionsValue参数控制value绑定所写的内容.所以,在你的情况下,它会返回isocodeselectedCountry.

因此,对代码的最简单更改是将selectedCountry设置为普通的observable和相应的isocode.然后,让你的跨度使用text绑定selectedCountry.

像这样:http://jsfiddle.net/wxNrt/21/

现在,您还可以使用其他几个选项: - 如果您optionsValue在绑定中离开,那么它将直接设置/读取对象.在这种情况下,您需要更改初始设置方式.

http://jsfiddle.net/wxNrt/23/

- 如果要发送/接收密钥(如isocode),则可以使用optionsValue,但设置dependentObservable来表示实际对象,如:

http://jsfiddle.net/wxNrt/22/

- 如果您正在处理多选情况,那么您希望使用selectedOptions绑定而不是value,如下所述:http: //knockoutjs.com/documentation/selectedOptions-binding.html