我正在尝试使用类似于此问题的optgroup绑定选择
KnockoutJS - Binding value of select with optgroup and javascript objects
不同之处在于页面上可能有一个或多个选项。所以我有类似的东西。
<script>
var services = ko.observableArray([
{ serviceId: 1 }, { serviceId: 2 }
]);
var servicesList = ko.observableArray([
{ Name: "Group 1", Services: [
{ Id: 1, Name: "One" },
{ Id: 2, Name: "Two" }
]},
{ Name: "Group 2", Services: [
{ Id: 3, Name: "Three" }
]}
]);
</script>
<div class="form-group" data-bind="foreach: services">
<label for="ServiceId" class="control-label col-md-2">Service</label>
<div class="col-md-10">
<select id="ServiceId" name="ServiceId" class="form-control" data-bind="foreach: servicesList, value: serviceId">
<optgroup data-bind="attr: {label: Name}, foreach: Services">
<option data-bind="text: Name, option: Id"></option>
</optgroup>
</select>
</div>
</div>
问题是未选择每个选项的值。
答案 0 :(得分:1)
serviceId在selectList中用作值,因此它应该是可观察的,而servicesList应该与父上下文一起使用。
//make observable to keep track selected value
self.services = ko.observableArray([{
serviceId: ko.observable(1)
}, {
serviceId: ko.observable(2)
}]);
//$parent.servicesList
<select id="ServiceId" name="ServiceId" class="form-control" data-bind="foreach: $parent.servicesList, value: serviceId">
<optgroup data-bind="attr: {label: Name}, foreach: Services">
<option data-bind="text: Name,value:Id, option: Id"></option>
</optgroup>
</select>