Knockout数据绑定下拉列表取决于其他下拉列表

时间:2014-10-14 12:55:58

标签: javascript data-binding knockout.js

我正在尝试数据化2个下拉列表,其中第二个下拉列表取决于第一个下拉列表中选择的内容。

我有这个数据结构:

{
EducationId: 1,
EducationCategories:[{
    Name: "Category1",
    Educations: [{
        Id: 1,
        Name: "Education1"
    }, {
        Id: 2,
        Name: "Education2"
    }]
}, {
    Name: "Category2",
    Educations: [{
        Id: 3,
        Name: "Education3"
    }, {
        Id: 4,
        Name: "Education4"
    }]
}]
}

这个我希望数据绑定到2个不同的“选择”与淘汰赛,所以我有1个下拉列表与所有类别名称,第二个与教育。

EducationId指的是所选择的教育,所以在数据示例中,第一个下拉列表是“Category1”,第二个是“Education1”。

但是,我如何才能使第二次下拉列表仅包含属于第一个下拉列表中所选类别的教育?然后将第二个下拉列表的值(id)绑定到EducationId。

数据由淘汰赛映射插件映射。

1 个答案:

答案 0 :(得分:1)

当第一个选定值更改时,使用computed属性更新第二个下拉列表。

例如:



var data = {
    EducationId: 1,
    EducationCategories :[{
        Name: "Category name1",
        Educations: [{
            Id: 1,
            Name: "Education name1"
        }, {
            Id: 2,
            Name: "Education name2"
        }]
    }, {
        Name: "Category name2",
        Educations: [{
            Id: 3,
            Name: "Education name3"
        }, {
            Id: 4,
            Name: "Education name4"
        }]
    }]
};

var viewModel = ko.mapping.fromJS(data);

viewModel.selectedCategory = ko.observable();
viewModel.Educations = ko.computed(function() {
    if (viewModel.selectedCategory()) {
        return viewModel.selectedCategory().Educations();
    }
});
viewModel.selectedEducation = ko.observable();

ko.applyBindings(viewModel);

<script src="https:////cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http:////cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>

<select data-bind="options: EducationCategories, value: selectedCategory, optionsText: 'Name'"></select>

<select data-bind="options: Educations, value: selectedEducation, optionsText: 'Name'"></select>
&#13;
&#13;
&#13;