2

我需要帮助来使用淘汰赛 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>
4

3 回答 3

4

正如你目前设置的那样,没有 foreach 可以工作。要正确设置您的 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>

小例子见小提琴

于 2012-10-03T13:35:44.963 回答
3

我正在使用嵌套数组,其中很难/无用地创建元素来绑定 foreach 语法。我喜欢这样的“无容器控制流语法”:

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

请参阅它的文档,在“注 4”下 http://knockoutjs.com/documentation/foreach-binding.html

于 2014-04-12T16:00:31.647 回答
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>
于 2012-10-03T10:30:02.897 回答