KnockoutJs绑定列表选项选择选项组

时间:2014-08-04 23:45:24

标签: javascript knockout.js knockout-2.0

我正在尝试使用类似于此问题的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>

问题是未选择每个选项的值。

1 个答案:

答案 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>

Fiddle Demo