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

时间:2011-08-01 16:14:39

标签: 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>

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);

另见this fiddle

2 个答案:

答案 0 :(得分:5)

optionsValue参数控制value绑定所写的内容。因此,在您的情况下,它会将isocode写入selectedCountry

因此,对代码的最简单更改是将selectedCountry设置为普通的observable和相应的isocode。然后,让您的跨度使用针对text的{​​{1}}绑定。

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

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

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

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

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

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

答案 1 :(得分:0)

我将你的标记更改为:

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

脚本:

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);

jsfiddle