knockoutjs依赖选择框问题绑定儿童选择框

时间:2013-07-14 19:55:40

标签: knockout.js

与knockoutjs购物车示例类似,我有一个包列表,价格取决于位置。我无法将依赖选择框(locationOptions)与视图绑定:

<select data-bind="options: packages,
                   optionsCaption: 'Select...',
                   optionsText: 'name',
                   value: selectedPackage">                 
</select>

<select data-bind="options: locationOptions,
                   optionsCaption: 'Select...',
                   optionsText: 'location',
                   value: selectedLocation">
</select>

<span data-bind="with: selectedPackage">
    <p>You have chosen <b data-bind="text: name"></b> (<span data-bind="text: description">)</span>
    In location <b data-bind="text: location"></b></p>
    <p>Total is <b data-bind="text: total"></b></p>
</span>

查看模型:

function viewModel(packages, addons) {
    this.packages = packages;
    this.selectedPackage = ko.observable();
    this.selectedLocation = ko.observable();
    this.total = ko.computed(function(){
        var x = 0;
        return x;
    });
}

这是jsfiddle http://jsfiddle.net/KN4P6/6/

1 个答案:

答案 0 :(得分:5)

查看this fiddle

<select data-bind="options: packages,
                   optionsCaption: 'Select...',
                   optionsText: 'name',
                   value: selectedPackage">                 
</select>

<!-- ko with : selectedPackage -->

<select data-bind="options: locationOptions,
                   optionsCaption: 'Select...',
                   optionsText: 'location',
                   value: $parent.selectedLocation">
</select>   

<!-- /ko  -->

<span data-bind="with: selectedPackage">
    <p>You have chosen <b data-bind="text: name"></b> (<span data-bind="text: description">)</span></p>
        <!-- ko with : $parent.selectedLocation -->
        In location <b data-bind="text: location"></b>
    <p>Total is <b data-bind="text: $parents[1].total"></b></p>
  <!-- /ko  -->
</span>

See fiddle

我希望它有所帮助。