Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout foreach with nested tables

I have a bit of a unique situation, I am hoping knockout js provides a way to accomplish this.

I have the following structure:

Order = function() {
    var self = this;
    self.Name = 'default';
}

Customer = function() {
     var self = this;
     self.Name = 'default';
     self.Orders = [];
}

I have the following table

<table>
    <thead>
        <tr>
            <th>Customer Name</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: CustomerArray">
        <tr>
            <td data-bind="text: Name"></td>
        </tr>
    </tbody>
</table>

So this is great, it gives me a list of all my customer names.

Now for step two, I MUST format the table in a way that it lists. Order Name, then Customer Name at the bottom:

Customer Name (TH LABEL)
Order1
Order2
Order3
Smith, Frank

I came up with the idea of nesting my order array by including a tbody inside of each customer iteration, but I don't like this approach since the column width's from order to customer won't align since they are different tables.

Does anyone have any good ways to solve my unusual problem?

Thank you!

like image 974
mvcNewbie Avatar asked May 20 '13 16:05

mvcNewbie


1 Answers

You could use "containerless control flow syntax" (Note 4 on the foreach docs) to render a TD for each order, then the customer, without a containing element:

<table>
    <thead>
        <tr>
            <th>Customer Name</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: CustomerArray">
        <!-- ko foreach: Orders -->
        <tr>
            <td data-bind="text: OrderDetails"></td>
        </tr>
        <!-- /ko -->
        <tr>
            <td data-bind="text: Name"></td>
        </tr>
    </tbody>
</table>

The commented block creates a binding scope just like the one on TBODY, but without the containing element.

like image 176
kevingessner Avatar answered Oct 10 '22 02:10

kevingessner