Reputation: 23
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>
Upvotes: 2
Views: 13035
Reputation: 966
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
Upvotes: 3
Reputation: 481
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.
Upvotes: 4
Reputation: 3529
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>
Upvotes: 2