Binding nested array using Knockout foreach

2019-07-16 11:50发布

I need assistance in binding nested array using knockout foreach.

Below is the code, would like to know how can I get the elements which is inside PatAppointments array.

 <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>

标签: knockout.js
3条回答
三岁会撩人
2楼-- · 2019-07-16 11:52

As you have you have it set up currently, no foreach would work. To set up your PatAppointments correctly, your object should look like

"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"
    }]
}]

And then as gbs has stated you'll want a foreach binding within another foreach binding as such:

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

See fiddle for small example.

查看更多
Root(大扎)
3楼-- · 2019-07-16 11:55

As you have one array nested in another, you need to define 2 foreach bindings in 2 nested html element (div, ul, tr, ...) like in the following example:

<div data-bind="foreach: appointment">
    <div data-bind="foreach: PatAppointments">
        <span data-bind="text: PatientName"></span>
    </div>
</div>
查看更多
太酷不给撩
4楼-- · 2019-07-16 12:02

I'm working with nested Arrays where it's difficult/useless to create elements just to bind the foreach syntax. I like the 'containerless control flow syntax' which looks like this:

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

See it's documentation, under 'Note 4' http://knockoutjs.com/documentation/foreach-binding.html

查看更多
登录 后发表回答