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
"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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With