我想使用 Knockout 将对象映射到表。首先,我将向您展示我的对象:
function tableViewModel() {
var self = this;
self.data = ko.observableArray();
self.data.push(
{
"Warnings": {
"numbers": 30,
"content": [
{
"number" : 3001,
"description" : "There may be a problem with the device you are using if you use the default profile"
},
{
"number" : 3002,
"description" : "There may be a problem with the device you are using if you don't use the default profile"
}
]
},
"Errors": {
"numbers": 20,
"content": [
{
"number": 1000,
"description": "No network is loaded"
},
{
"number": 1000,
"description": "No network is loaded"
}
]
}
}
);
self.dataTitle = ko.observable("Warnings")
}
ko.applyBindings(tableViewModel());
该对象包含两个“对象”,警告和错误。我希望能够在淘汰赛中,取决于一个变量(在这种情况下是变量 dataTitle),仅显示警告的内容(如果 dataTitle ==“警告”)或错误的内容。
基本上,我希望它查找与 dataTitle 的内容相对应的对象。
我正在尝试实现这样的目标,但显然它不起作用:
<table class="table table-hover" data-bind="foreach: data">
<thead>
<tr>
<th style="width:100px">Numero</th>
<th>Description</th>
</tr>
</thead>
<tbody data-bind="foreach: data[dataTitle].content"> <!-- This line is not giving expected results -->
<tr>
<td data-bind="text: $data.number"></td>
<td data-bind="text: $data.description"></td>
</tr>
</tbody>
</table>
这是一个代表问题的 JSFiddle:http: //jsfiddle.net/etiennenoel/bqcMR/
我的问题是:有没有办法使用 KnockoutJS 来做到这一点,或者要求太多?