与挖空框架的组合框绑定不正确



Helo 大家

我已经创建了带有表格的简单页面,并希望使用挖空框架用数据填充它。

该表包含三列,用于显示基础视图模型中的数据。一般来说这是有效的,但我对第一列(允许选择当前项目的组合框)有一点问题:我想将"数字"属性显示为组合标题并在绑定中指定属性名称,但显示值"[对象对象]"而不是数字属性。

那么,我的绑定有什么问题。如何正确显示"数字"属性?

谢谢。

页面代码在这里:

<head>
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js" type="text/javascript"></script>
</head>
<body>
<button data-bind="click: addItem">Add product</button>
    <table>
        <thead>
            <tr>
                <th>Number</th>
                <th>Name</th>
                <th>Count</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: itemsData">
            <tr>
                <td>
                    <select data-bind="options: $root.avaliableItems, optionsText: $data.number, optionsCaption: 'Select...', value: tableItem"> </select>
                </td>
                <td data-bind="with: tableItem">
                    <span data-bind="text: name"> </span>
                </td>
                <td>
                    <input data-bind="value: count" />
                </td>
            </tr>
        </tbody>
    </table>
    <script type="text/javascript">
        function TableItem(number, name){
            var self = this;
            self.number = ko.observable(number);
            self.name = ko.observable(name);
        };
        function ExtendedItem(){
            var self = this;
            self.tableItem = ko.observable();
            self.count = ko.observable(1);
        };
        function SampleViewModel(){
            var self = this;
            self.avaliableItems = [
                new TableItem("Num1", "Item 1 name"),
                new TableItem("Num2", "Item 2 name"),
                new TableItem("Num3", "Item 3 name"),
                new TableItem("Num4", "Item 4 name"),
                new TableItem("Num5", "Item 5 name"),
                new TableItem("Num6", "Item 6 name"),
                new TableItem("Num7", "Item 7 name")
            ];
            self.itemsData = ko.observableArray();
            self.addItem = function(){
                self.itemsData.push(new ExtendedItem());
            };
        };
        ko.applyBindings(new SampleViewModel());
    </script>
</body>

您的选择应如下所示:

<select data-bind="options: $root.avaliableItems, optionsText: 'number', optionsCaption: 'Select...', value: tableItem"> </select>

请注意使用 optionsText ,它需要一个字符串(标识属性名称)。

这是一个小提琴,演示:http://jsfiddle.net/jearles/5qakM/

有关更多详细信息,请阅读选项绑定文档。

最新更新