使用Knockout foreach绑定嵌套数组

时间:2012-10-03 09:53:49

标签: knockout.js

我需要协助使用knockout foreach绑定嵌套数组。

下面是代码,想知道如何获取PatAppointments数组中的元素。

 <script language="javascript" type="text/javascript">
 ko.applyBindings({
    "appointment": [{
        "Date": "01\/10\/2012",
        "PatAppointments": [{
            "EndTime": "11:15:00",
            "EventId": null,
            "Facility": "General Physician",
            "PatientID": 23,
            "PatientName": "Vicki"
        }],
        "PatAppointments": [{
            "EndTime": "11:15:00",
            "EventId": null,
            "Facility": "General Physician",
            "PatientID": 23,
            "PatientName": "Scott"
        }]
    }]
});

</script>

<table>
<tbody data-bind="foreach: appointment">
<tr>
    <td data-bind="text: Date">
    </td>
</tr>
<tr>
    <td>
         @*
        <tbody data-bind="foreach: appointment.PatAppointments">
        <tr>
            <td data-bind="text: PatAppointments.PatientName">
            </td>
            <td data-bind="text: PatAppointments.Facility">
            </td>
        </tr>
        </tbody>
        *@
    </td>
</tr>
</tbody>
</table>

3 个答案:

答案 0 :(得分:4)

正如你所拥有的那样,目前没有任何预设可行。要正确设置PatAppointments,您的对象应该看起来像

"appointment": [{
    "Date": "01\/10\/2012",
    "PatAppointments": [
    {
        "EndTime": "11:15:00",
        "EventId": null,
        "Facility": "General Physician",
        "PatientID": 23,
        "PatientName": "Vicki"
    },
    {
        "EndTime": "11:15:00",
        "EventId": null,
        "Facility": "General Physician",
        "PatientID": 23,
        "PatientName": "Scott"
    }]
}]

然后正如gbs所说,你需要在另一个foreach绑定中绑定foreach

<div data-bind="foreach: appointment">
    <div data-bind="foreach: PatAppointments">
        //Everything you want displayed from each PatAppointment here.
    </div>
</div>

有关小例子,请参阅fiddle

答案 1 :(得分:3)

我正在使用嵌套数组,在这种情况下创建元素只是为了绑定foreach语法很困难/无用。我喜欢无容器控制流语法&#39;看起来像这样:

<!-- ko foreach: appointment -->
    <!-- ko foreach: PatAppointments -->
        <span data-bind="text: PatientName"></span>
    <!-- /ko -->
<!-- /ko -->

请参阅&#39;注4&#39; http://knockoutjs.com/documentation/foreach-binding.html

答案 2 :(得分:2)

由于您有一个嵌套在另一个数组中的数组,您需要在2个嵌套的html元素(div,ul,tr,...)中定义2 foreach 绑定,如下例所示:

<div data-bind="foreach: appointment">
    <div data-bind="foreach: PatAppointments">
        <span data-bind="text: PatientName"></span>
    </div>
</div>