在Knockoutjs级联下拉列表中设置OptionValue

时间:2012-07-23 17:39:58

标签: knockout.js

有一个奇怪的问题,一切正常,直到我指定optionsValue。你可以在这里看到我的问题

工作原理 http://jsfiddle.net/abritez/ttyhE/2/

不起作用 http://jsfiddle.net/abritez/ttyhE/4/

您需要做的就是尝试使用已注释的选项运行它,并且在尝试级联时会看到问题。

JSON数据

var productCategories = [{
"name": "Comapany A",
"abbr": "cA",
"disiplineList": [{
    "name": "Math",
    "abbr": "math",
    "courseList": [{
        "name": "Algebra",
        "abbr": "alg"
    }]
}, {
    "name": "English",
    "abbr": "eng",
    "courseList": [{
        "name": "Phonics",
        "abbr": "phon"
    }]
}]
}, {
"name": "Company B",
"abbr": "cB",
"disiplineList": [{
    "name": "Gym",
    "abbr": "gym",
    "courseList": [{
        "name": "Kick Ball",
        "abbr": "kb"
    }]
}]
}];

HTML代码

<table width='100%'>
<tbody data-bind='foreach: lines'>
  <tr>
         <td>

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

        </td>
    </tr>
    <tr>
         <td data-bind="with: company">
            <select data-bind='options: disiplineList, optionsText: "name", optionsCaption: "Select...", value: disipline'> </select>
        </td>
    </tr>
     <tr>
         <td data-bind="with: disipline">
            <select data-bind='options: courseList, optionsText: "name",  value: product'></select>
        </td>
    </tr>

</tbody>
</table>

Java Script(knockoutjs)

function ProductLine(){
                    self.company = ko.observable();
                    self.disipline = ko.observable();
                    self.product = ko.observable();

                    // Whenever the category changes, reset the product selection
                    self.company.subscribe(function() {
                        self.disipline(undefined);
                        self.product(undefined);
                    });
                }

                function Product(){
                    self.lines = ko.observableArray([new ProductLine()]); // Put one line in by default
                }

                ko.applyBindings(new Product());​

1 个答案:

答案 0 :(得分:1)

我仍然没有得到它。

但是如果你想显示名字而 abbr 你可以:

 <select data-bind='options: productCategories,
       optionsText: function(item) {return item.name + " - " + item.abbr},  optionsCaption: "Select...", value: company'> </select>

如果你想显示 abbr ,你可以:

<td data-bind="with: company">
                            <select data-bind='options: disiplineList, optionsText: "name", optionsCaption: "Select...", value: disipline'> </select>
                             <span data-bind="text: abbr"/> <-- like this
                        </td>