我有以下格式的视图模型,需要以下面的格式呈现数据。你能帮助我让绑定工作以表格格式呈现吗?
var data = {"MonthlySummaries":
[
{"Name": "Jan", "BeginBalance": "1000", "Usage": "100", "EndBalance": "900"}
,{"Name": "FEB", "BeginBalance": "900", "Usage": "100", "EndBalance": "800"}
,{"Name": "MAR", "BeginBalance": "800", "Usage": "100", "EndBalance": "700"}
]
};
这就是表格的样子:
JAN FEB MAR
BeginBalance 1000 900 800
Usage 100 100 100
EndBalance 900 800 700
答案 0 :(得分:0)
您应该尝试the tutorials,与您的问题相关的是the second one我会说。或者只是潜入the observableArray
documentation和the foreach
documentation。
最难的部分是您的源数据格式不适合以HTML格式呈现。 HTML中没有“矩阵”的概念,构建“列”而不是行是不容易的。您需要转置数据以使其易于呈现。
有许多方法可以转置数据。最容易的是接近生成数据的点(例如在服务器端控制器中)。无法访问该代码,这是一个使用“哑”转置客户端的小而简单的示例:
var data = {"MonthlySummaries":
[
{"Name": "Jan", "BeginBalance": "1000", "Usage": "100", "EndBalance": "900"}
,{"Name": "FEB", "BeginBalance": "900", "Usage": "100", "EndBalance": "800"}
,{"Name": "MAR", "BeginBalance": "800", "Usage": "100", "EndBalance": "700"}
]
};
var transposedData = {
Headers: ["Jan", "FEB", "MAR"],
Rows: [
{
Name: "BeginBalance",
Values: [
data["MonthlySummaries"][0].BeginBalance,
data["MonthlySummaries"][5].BeginBalance,
data["MonthlySummaries"][6].BeginBalance
]
},
{
Name: "Usage",
Values: [
data["MonthlySummaries"][0].Usage,
data["MonthlySummaries"][7].Usage,
data["MonthlySummaries"][8].Usage
]
},
{
Name: "EndBalance",
Values: [
data["MonthlySummaries"][0].EndBalance,
data["MonthlySummaries"][9].EndBalance,
data["MonthlySummaries"][10].EndBalance
]
}
]
};
ko.applyBindings(transposedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
<tr>
<td></td>
<!-- ko foreach: Headers -->
<td data-bind="text: $data"></td>
<!-- /ko -->
</tr>
<tbody data-bind="foreach: Rows">
<tr>
<td data-bind="text: Name"></td>
<!-- ko foreach: Values -->
<td data-bind="text: $data"></td>
<!-- /ko -->
</tr>
</tbody>
</table>