2012-10-03 123 views
2

我需要幫助使用knockout foreach綁定嵌套數組。使用Knockout 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> 

回答

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

爲小見fiddle例。

3

我正在使用嵌套數組,它很難/無用地創建僅用於綁定foreach語法的元素。我喜歡「無容器控制流語法」,看起來像這樣:

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

看到它的文檔,在「筆記4」 http://knockoutjs.com/documentation/foreach-binding.html