Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js containerless "foreach" not working with <table>

This code throws the error (in Chrome): "Cannot find closing comment tag to match: ko foreach: MyPlans":

<table>   <!-- ko foreach: MyPlans -->     <tr>       <td>Test</td>     </tr>   <!-- /ko --> </table> 

If I use a list instead, everything works:

<ul>   <!-- ko foreach: MyPlans -->     <li>       Test     </li>   <!-- /ko --> </ul> 

I would like to use the containerless foreach with a table. Is there something I'm doing wrong? Is it a bug?

like image 414
Jag Avatar asked Nov 14 '11 00:11

Jag


People also ask

What is KnockoutJS-foreach binding?

KnockoutJS - Foreach Binding - In this binding, each array item is referenced in HTML markup in a loop. This is very useful while populating a list or table data. foreach can be nested along

What are the parameters of knockout in JavaScript?

Knockout will supply the following parameters to your callback: beforeMove — is invoked when an array item has changed position in the array, but before the corresponding DOM nodes have been moved.

How does knockout work?

Knockout understands this virtual element syntax and binds as if you had a real container element. When you modify the contents of your model array (by adding, moving, or deleting its entries), the foreach binding uses an efficient differencing algorithm to figure out what has changed, so it can then update the DOM to match.

How to hide destroyed items in an array in knockout?

By default, the foreach binding will show all array entries, even those that are marked as destroyed. If you want to hide destroyed entries, set the includeDestroyed option to false. For example, ... Prior to Knockout 3.5.0, the default behavior was to hide destroyed items.


1 Answers

This is related to the fact that browsers insert tbody tags automatically, which creates a mismatch in the comments. The rendered output will look like:

<table>   <!-- ko foreach: MyPlans -->   <tbody>     <tr>       <td>Test</td>     </tr>   <!-- /ko -->   </tbody> </table> 

Steve did put some work into trying to correct mismatched tags in KO, but the easiest thing for you to do is either add the tbody yourself or add the tbody and put your binding on it.

<table>   <tbody data-bind="foreach: MyPlans">     <tr>       <td>Test</td>     </tr>   </tbody> </table> 

It is legal for a table to have multiple tbody tags, if necessary.

like image 52
RP Niemeyer Avatar answered Sep 19 '22 15:09

RP Niemeyer