如何将Knockout模型数据绑定到多个表

时间:2015-08-05 06:34:53

标签: html knockout.js

我正在使用knockout绑定将一些数据绑定到html表中。我的淘汰视图模型有多个产品,每个产品都有多个字符。我想在一个表格中显示产品,当我选择链接" show chars"它应该在下表中显示相应的字符。

这是我的视图模型

var ProductViewModel = function(items) {
    this.items = ko.observableArray(items);
    this.itemToAdd = ko.observable("");
    this.addItem = function() {
        if (this.itemToAdd() != "") {
            this.items.push(this.itemToAdd()); 
            this.itemToAdd(""); 
        }
    }.bind(this);
};

这是我的html表

<div id="productTable">
        <table  class="ui-responsive table">
            <thead>
                <tr>
                    <th >Product Name</th>
                    <th >Description</th>
                    <th >Parent?</th>
                </tr>
            </thead>
            <tbody id="pBody" data-bind="foreach: items">
                <tr class="success" >
                    <td><span data-bind="text: name"></span>

                    </td>
                    <td><span data-bind="text: desc"></span>

                    </td>
                    <td><a href="#" onclick="showChars();return false;">show chars</a></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<div id="productChars">
    <div id="productCharTable">
        <table  class="ui-responsive table">
            <thead>
                <tr>
                    <th >Char Name</th>
                    <th >Description</th>
                    <th >Length</th>
                    <th >Type</th>
                </tr>
            </thead>
            <tbody id="pBody" data-bind="foreach: $data['chars']">
                <tr class="success">
                    <td><span data-bind="text: name"></span>
                    </td>
                    <td>asdf asdfasdf</td>
                    <td>10</td>
                    <td>String</td>
                </tr>
            </tbody>
        </table>
    </div>

我能够将产品绑定到第一个表中。但对于特征我不知道如何实现同样的目标。

有人可以帮我弄清楚如何实现同样目标。

这是jsfiddle https://jsfiddle.net/sirisha_k/0Ln7h2bo/7/

1 个答案:

答案 0 :(得分:0)

正如@supercool指出的那样,你可以使用“data-bind ='和selectedItem'”来用chars数据填充第二个表。为此,您需要在模型中再添加一个名为selectedItem的项目,并且每次选择或添加行时,都会将selectedItem指向该元素数据。并对第二个表使用“data-bind ='with selecteItem'”。

render="t:@rows(row)"

};

并在行上选择调用一些函数selectedItem($ data),其中$ data指的是当前项。

然后将该数据设置为模型中的selectedItem。

var ProductViewModel = function(items) {
this.items = ko.observableArray(items);
this.selectedItem = ko.observableArray();
this.itemToAdd = ko.observable("");
this.addItem = function() {
    if (this.itemToAdd() != "") {
        this.items.push(this.itemToAdd()); 
        this.itemToAdd(""); 
    }
}.bind(this);