两个基于ID knockoutjs的下拉选项绑定

时间:2014-03-19 19:16:04

标签: javascript knockout.js knockout-2.0 knockout-mapping-plugin knockout-mvc

我有以下内容:

     <select data-bind="options: animals, value: optionsValue: 'ID', optionsText: 'Name'" />

        self.animals = ko.mapping.fromJS([
            {"Name": "Tamed": , "ID": "1" },
            {"Name": "Wild": , "ID": "2" },
            ]);

        self.wildOrTamed = ko.mapping.fromJS([
            { "Name": "Cat", "ID": "1" },
            { "Name": "Lion", "ID": "2" },
            { "Name": "Cat": "1"  },
            { "Name": "Tiger", "ID": "2"  }]);

我希望这有2个下拉动物来选择Tamed或Wild,然后根据该更改我的wildOrTamed下拉以显示使用指定ID的野生动物或驯服动物。

注意:这是动态的,所以可能有其他类型的动物......

任何人都可以帮我解决这个问题。

由于

2 个答案:

答案 0 :(得分:3)

尝试使用computed observable。查看小提琴http://jsfiddle.net/aravindbaskaran/6w4N8/

<select data-bind="options: animalTypes, value: animalType, optionsValue: 'ID', optionsText: 'Name'"></select>
<select data-bind="options: animalsForType, value: selectedAnimal, optionsValue: 'ID', optionsText: 'Name'"></select>

self.animalTypes = ko.observable([{"Name": "Tamed","ID": "1"},
    {"Name": "Wild","ID": "2"},
    {"Name": "Something else","ID": "3"}]);

self.animals = [{"Name": "Cat","ID": "1"},
    {"Name": "Lion","ID": "2"},
    {"Name": "Cat","ID": "1"}, 
    {"Name": "Tiger","ID": "2"}];
self.animalType = ko.observable();
self.selectedAnimal = ko.observable();
self.animalsForType = ko.computed(function () {
    var selectedType = self.animalType();
    return !selectedType ? [] : self.animals.filter(function (animal) {
        return animal.ID == selectedType;
    });
});

希望它有所帮助!

答案 1 :(得分:0)

您好我不是100%肯定,但是以下链接可以帮助您创建级联下拉菜单。 http://www.dotnetexpertguide.com/2012/06/cascading-dropdown-knockoutjs-aspnet.html