Knockout SelectedOptions绑定到对象的属性失败

时间:2017-05-11 15:00:51

标签: javascript knockout.js

我在敲除options绑定时遇到问题,特别是一个多选selectedOptions映射到ko.observable的属性这是html:

<select data-bind="options: disabilities, optionsValue: 'id', selectedOptions: 'currentBusType().disabilities', optionsText: 'code'" multiple="true" size="5"></select>

disabilitiesko.observableArray,具有以下结构:

[
  {"id":"1","code":"WC","description":"Wheel Chair"},
  {"id":"2","code":"SN","description":"Special Needs"}
]

currentBusType是具有以下结构的ko.observable

{
  "bustype_id":"2",
  "name":"Bus Type 2",
  "capacity":"20",
  "serial_number":null,
  "disabilities":[1,2]
}

根据对DOM的检查,结果是多选,其值和选项正确但未正确预选选项。我该怎么做这个绑定,我做错了什么?

1 个答案:

答案 0 :(得分:2)

首先,您需要删除表达式周围的单引号:

selectedOptions: currentBusType().disabilities

然后,您需要确保每个残疾id的类型与currentBusType.disabilities中的类型相匹配。目前,一个是Number,另一个是String。因此,如果您更改disabilities,它将如下所示:

"disabilities": ["1", "2"]

请参阅Fiddle