Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout.js foreach repeats td element in table, but not the tr element

I have the following excerpt from a table that I'm using to display a lot of files retrieved from a server, using MVC 4 and the knockout.js library version 2.1.0.

    <tr data-bind="foreach: files, visible: (files() && files().length > 0)">
        <td data-bind="text: UploadPath" />
        <td data-bind="text: FileName" />
    </tr>

The data is being retrieved properly, however foreach is repeating the TD elements in the table and not the TR. So if there are 100 files, there will be 200 columns in the table displayed to the user. How do I make the TR element repeat foreach file?

like image 240
Shawn Gilligan Avatar asked Aug 24 '12 14:08

Shawn Gilligan


2 Answers

Simply put the "foreach" binding in the next (outer) element:

<table data-bind="foreach: files, ...">
    <tr>
        ...

You can also utilize a virtual element:

<!-- ko foreach: files -->
<tr>
    <td>
        ...
</tr>
<!-- /ko -->
like image 109
Niko Avatar answered Jan 02 '23 15:01

Niko


I came across a strange thing:

I was trying to use a containerless binding to repeat multiple table rows. KO complained that it couldn't find the closing /ko tag .

I had a table-header defined above the containerless binding. If I changed this to a standard table row everything worked as expected (except my header didn't have the required styling but I override that).

Hope this helps someone else struggling with this - it's only a workaround rather than a fix.

like image 37
mhall Avatar answered Jan 02 '23 14:01

mhall