问题描述:

Bit new to knockout so I seem to be struggling with this grouping.

The server returns the following json

{"EmployeeData":[{"Id":1,"EmployeeName":"AA Guy1","EmployeeNumber":1004,"Department":1},{"Id":2,"EmployeeName":"BB Guy2","EmployeeNumber":1004,"Department":2},{"Id":3,"EmployeeName":"CC Guy3","EmployeeNumber":1004,"Department":2},{"Id":4,"EmployeeName":"DD Guy4","EmployeeNumber":1004,"Department":3},{"Id":5,"EmployeeName":"EE Guy5","EmployeeNumber":1004,"Department":1},{"Id":6,"EmployeeName":"FF Guy6","EmployeeNumber":1004,"Department":3}],"Dpts":[{"Id":1,"Name":"First Level Department","Desc":"1st somewhere out there"},{"Id":2,"Name":"Finance services","Desc":"Show me the money"},{"Id":3,"Name":"HR Department","Desc":"No education needed"}]}

I then have a table which has

<tbody data-bind="foreach: GroupEmployees" >

<tr class="employee-row">

<td>

<strong>

<span data-bind="text: EmployeeName"></span>

</strong>

</td>

<td>

<span data-bind="text: EmployeeNumber"></span>

</td>

<td>

<span data-bind="text: Department" />

</td>

</tr>

</tbody>

this showed the employee and just department number,....

I added the dpts to json, and i now have to get it to group by department. so it has to have a department heading - and under that list all employees in that department, then repeat for each department..

Im struggling to see how to get this right.

It's probably simple for somebody with more knockout experience.

网友答案:

The easiest way I can see for you to achieve this is to modify your data to look like this:

{
  "Dpts" : [
      {
          "Name" : "Finance",
          "EmployeeData" : 
          [
             { "Id":"1", "EmployeeNumber":1001 },
             { "Id":"2", "EmployeeNumber":1002 },
             { "Id":"3", "EmployeeNumber":1003 }
          ]
      },
      {
          "Name" : "HR",
          "EmployeeData" : 
          [
             { "Id":"4", "EmployeeNumber":1004 },
             { "Id":"5", "EmployeeNumber":1005 },
             { "Id":"6", "EmployeeNumber":1006 }
          ]
      },
  ]
}

And then have two nested knockout "foreach"'s:

<tbody data-bind="foreach: Dpts" >
<tr>
  <td>
    <strong>
       <span data-bind="text: Name"></span>
    </strong>
  </td>
  <td>
     <table>
       <tbody data-bind="foreach: EmployeeData">
       ...
       </tbody>
     </table>
  </td>
</tr>
</tbody>
相关阅读:
Top