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>
As you have you have it set up currently, no foreach would work. To set up your PatAppointments correctly, your object should look like
And then as gbs has stated you'll want a
foreach
binding within anotherforeach
binding as such:See fiddle for small example.
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:
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:
See it's documentation, under 'Note 4' http://knockoutjs.com/documentation/foreach-binding.html