0

好的,我正试图了解 knockoutjs 嵌套下拉菜单。

基本上我想从绑定的下拉列表 a 中选择一个选项,并让下拉列表 b 显示相关选项。

这是我从淘汰赛教程中摘录并修改的模型:

 function SeatReservation(name, initialMeal) {
            var self = this;
            self.name = name;
            self.meal = ko.observable(initialMeal);
        }

        // Overall viewmodel for this screen, along with initial state
        function ReservationsViewModel() {
            var self = this;

            // Non-editable catalog data - would come from the server
            self.availableMeals = ko.observableArray([
                { mealName: "Standard (sandwich)", price: 0, Sizes: [{ Desc: "large" }, { Desc: "medium" }, { Desc: "small" }] },
                { mealName: "Premium (lobster)", price: 34.95, Sizes: [{ Desc: "large1" }, { Desc: "medium1" }, { Desc: "small1" }] },
                { mealName: "Ultimate (whole zebra)", price: 290, Sizes: [{ Desc: "large2" }, { Desc: "medium2" }, { Desc: "small2" }] }
            ]);


            // Editable data
            self.seats = ko.observableArray([
                new SeatReservation("Steve", self.availableMeals[0]),
                new SeatReservation("Bert", self.availableMeals[0])
            ]);


        }

        ko.applyBindings(new ReservationsViewModel());

然后我的html:

<tbody data-bind="foreach: seats">
    <tr>
        <td><input data-bind="value: name" /></td>
        <td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
         <td data-bind="with: $root.availableMeals">
                    <select data-bind='options: $parent.Sizes, optionsText: "Desc", optionsCaption: "Select...", value: Desc'> </select>
                </td>
        <td data-bind="text: meal().price"></td>
    </tr>    
</tbody>

现在我知道我的 html 可能不正确,因为我已经搞砸了很多尝试让这个工作但基本上我想从下拉列表中选择一顿饭,并在第二个下拉列表中显示其相关尺寸......

我究竟做错了什么?!

4

1 回答 1

0

目前,所有SeatReservation对象都可能指向availableMeal项目的相同副本。

如果每个预留都能够自定义“大小”,那么您可能希望将大小存储在预留对象上。也许像:

function SeatReservation(name, initialMeal) {
  var self = this;
  self.name = name;
  self.meal = ko.observable(initialMeal);
  self.size = ko.observable();
}

然后你可以像这样绑定:

  <td data-bind="if: meal">
    <select data-bind='options: meal().Sizes, optionsText: "Desc", optionsCaption: "Select...", optionsValue: "Desc", value: size'></select>
  </td>

示例:http: //jsfiddle.net/rniemeyer/HsDeG/

于 2013-01-11T23:18:09.800 回答