Sebazzz
Sebazzz

Reputation: 1373

Knockout: Template instantiation in same HTML element

Given a view model with the following structure:

- Root
    - Rows []
       - Record
       - Values[]
           - Source
           - Target

I'd like to put this in a table like this:

<table>
<thead>
     <tr><th>#</th><th>Source</th><th>Target</th></tr>
</thead>
<tbody data-bind="foreach: Rows">
    <tr>
        <td data-bind="text: Record"></td>
        <td colspan="2"></td>
    </tr>

    <tr>
        <!--- This row should repeat for every item in 'Values' --->
        <td>&nbsp;</td>
        <td data-bind="text:Source"></td>
        <td data-bind="text:Target"></td>
    </tr>
</tbody>
</table>

Is this possible with knockout? If not, what are my alternatives? I want to put the values of the 'Values' array in the same table, to ensure that the columns will properly resize with the columns in the table head.

Upvotes: 0

Views: 71

Answers (1)

Romain B.
Romain B.

Reputation: 266

You can use a knockout virtual element with foreach binding on it :

    <table>
    <thead>
         <tr><th>#</th><th>Source</th><th>Target</th></tr>
    </thead>
    <tbody data-bind="foreach: Rows">
        <tr>
            <td data-bind="text: Record"></td>
            <td colspan="2"></td>
        </tr>

    <!-- ko foreach: Values -->
        <tr>
            <td>&nbsp;</td>
            <td data-bind="text:Source"></td>
            <td data-bind="text:Target"></td>
        </tr>
    <!-- /ko -->  
    </tbody>
    </table>  

Ref: Using text without a containing element

Upvotes: 2

Related Questions