我正在尝试在另一个foreach中添加一个foreach过滤器,假设我有一个与Employees的第一个foreach,我需要根据员工编号添加另一个foreach,所以对于每个员工我需要过滤与每个相关的订单一。如何在我的视图中按员工编号过滤我的第二个foreach并循环完成所有员工订单?
这是我的观点:
<div>
<table id="employee-table">
<thead>
<tr>
<th style="width: 15px" class="sorting_disabled"></th>
<th class="sorting_disabled">"EmployeeName"</th>
<th class="sorting_disabled">EmployeeNumber</th>
<th class="sorting_disabled">Address</th>
<th class="sorting_disabled">EmployeePosition</th>
<th class="sorting_disabled">OfficeName</th>
<th class="sorting_disabled">TotalCharges</th>
</tr>
</thead>
<tbody>
<!-- ko foreach: model.employeeList() -->
<tr>
<td data-bind="css: { 'dashboard-collapsed-triangle': $data.numberOfOrders > 0 },
click: function () { $('#employee-service-cost-table' + $data.employeeId).toggle(); $(this).toggleClass('dashboard-collapsed-triangle dashboard-expanded-triangle') }" >
</td>
<td><a href="#tips"><span class="dashboard-employee-selectable" data-bind="text: $data.employeeName"></span></a></td>
<td><span data-bind="text: $data.employeeNumber"></span></td>
<td><span data-bind="text: $data.address"></span></td>
<td><span data-bind="text: $data.employeePosition"></span></td>
<td><span data-bind="text: $data.officeName"></span></td>
<td><span data-bind="text: $data.totalCharges"></span></td>
</tr>
<!-- HERE I NEED A SECOND FOREACH -->
<tr style="display: none; background-color: aliceblue" data-bind="attr: { 'id': 'employee-service-cost-table' + $data.employeeId }">
<td></td>
<td colspan="3"><span data-bind="text: $data.OrderNumber"></span></td>
<td><span data-bind="text: $data.Description"></span></td>
<td><span data-bind="text: $data.TotalCharges"></span></td>
<td><span data-bind="text: $data.Date"></span></td>
</tr>
<!-- END SECOND FOREACH -->
<!-- /ko -->
</tbody>
</table>
答案 0 :(得分:0)
因此,如果我理解正确,您将拥有一份员工清单和一份订单清单。然后,一名员工可以根据员工ID获得多个订单?
执行此操作的一种方法是按员工ID分组订单:
model.ordersByEmployeeId = ko.computed(function() {
var ordersByEmployeeId = {};
ko.utils.arrayForEach(model.orders(), function(order) {
var employeeId = ko.unwrap(order.employeeId);
if (!ordersByEmployeeId[employeeId]) {
ordersByEmployeeId[employeeId] = [];
}
ordersByEmployeeId[employeeId].push(order);
});
return ordersByEmployeeId;
});
然后你的循环看起来如下:
<!-- ko foreach: model.employeeList() -->
...
<!-- ko foreach: $root.ordersByEmployeeId()[$data.employeeId] -->
...
答案 1 :(得分:0)
您可以将$ data参数传递给第二级foreach。
如果您将订单保存在单独的数组中,请使用:
<!-- ko foreach: getOrders($data.employeeId) -->
其中getOrders是一个过滤掉特定员工订单的功能。