我有这个选择字段:
<select data-bind="foreach: $root.feeGroups, value: $root.selectedFee">
<optgroup data-bind="attr: {label: label}, foreach: fees">
<option data-bind="text: description, option: $data"></option>
</optgroup>
</select>
feesGroup
属性:
self.feeGroups([
{ label: "NEW", fees: self.fees().filter(f => f.status === "New") },
{ label: "OLD", fees: self.fees().filter(f => f.status === "Old") }
]);
binding handler
:
ko.bindingHandlers.option = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
console.log(ko.toJSON(value));
ko.selectExtensions.writeValue(element, value);
}
};
我的问题在于&#34; optionsCaption&#34;,因为我使用foreach方法生成内部选项,它不会像我能够使用&#34那样自动工作;选项&#34;捆绑。但我确实需要一个&#34;请选择......&#34;默认选项。
有办法吗?
答案 0 :(得分:1)
您可以将foreach
绑定移动到虚拟元素,并在视图中添加一个代表null
值的额外选项:
<select data-bind="value: selectedFee">
<option data-bind="text: 'Select an option', option: null"></option>
<!-- ko foreach: feeGroups -->
...
<!-- /ko -->
</select>
请注意,当占位符处于活动状态时,selectedFee
可观察对象将包含null
。
// From: https://stackoverflow.com/a/11190148/3297291
ko.bindingHandlers.option = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
ko.selectExtensions.writeValue(element, value);
}
};
const fees = [
{ type: "old", description: "test1" },
{ type: "old", description: "test2" },
{ type: "new", description: "test3" },
{ type: "new", description: "test4" }
];
const feeGroups = [
{ label: "new", fees: fees.filter(f => f.type === "new") },
{ label: "old", fees: fees.filter(f => f.type === "old") }
];
const selectedFee = ko.observable(null);
selectedFee.subscribe(console.log.bind(console, "new selection:"));
ko.applyBindings({ feeGroups, selectedFee });
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="value: selectedFee">
<option data-bind="text: 'Select an option', option: null"></option>
<!-- ko foreach: feeGroups -->
<optgroup data-bind="attr: {label: label}, foreach: fees">
<option data-bind="text: description, option: $data"></option>
</optgroup>
<!-- /ko -->
</select>
&#13;