Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new row every 2 records using knockout foreach

I'm attempting to create a new row every two records using knockout virtual elements. My problem is that the odd record does not generate in between the two even indexes.

Here's my source HTML

   <!--ko foreach:UDGroupboxes-->
    <!--ko if:$index()%2==0 || $index()==0-->
    <div class="row-fluid">
    <!--/ko-->
        <div class="panel form-horizontal span6">
            <div class="panel-heading"><span data-bind="text:$data.Caption"></span></div>
        </div>
     <!--ko if:$index%2()!=0 && $index()!=0-->
    </div>
    <!--/ko-->
    <!--/ko-->

The output HTML

<div data-bind="attr:{id:Name}" class="tab-pane active" id="Tabsheet1">
    <!--ko foreach:UDGroupboxes-->
    <!--ko if:$index()%2==0 || $index()==0-->
    <div class="row-fluid">
    <!--/ko-->
        <div class="panel form-horizontal span6">
            <div class="panel-heading"><span data-bind="text:$data.Caption"></span></div>
        </div>
     <!--ko if:$index%2()!=0&&$index()!=0-->
    </div>
    <!--/ko-->

    <!--ko if:$index()%2==0 || $index()==0--><!--/ko-->

    <!--ko if:$index()%2==0 || $index()==0-->
    <div class="row-fluid">
    <!--/ko-->
        <div class="panel form-horizontal span6">
            <div class="panel-heading"><span data-bind="text:$data.Caption"></span></div>
        </div>
     <!--ko if:$index()%2!=0&&$index()!=0-->
    </div>
    <!--/ko-->
    <!--/ko-->
</div>

The panel should be generated no matter the condition. The condition only determines to open a new row on even numbers and close the row on odds.

like image 346
Strake Avatar asked Feb 16 '23 15:02

Strake


1 Answers

Knockout binding only happen on elements, and virtual elements must also adhere to the element hierarchy. If we take your example and use indentation to show the element relation, it looks like this:

<!--ko foreach:UDGroupboxes-->
    <!--ko if:$index()%2==0-->
        <div class="row-fluid">
            <!--/ko-->
            <div class="panel form-horizontal span6">
                <div class="panel-heading"><span data-bind="text:$data.Caption"></span></div>
            </div>
            <!--ko if:$index()%2!=0-->
        </div>
    <!--/ko-->
<!--/ko-->

The closing and opening virtual tags within the div are ignored by Knockout. So the above just has the effect of outputting every other item.

Here is a good answer for doing grouping of array items in Knockout: https://stackoverflow.com/a/10577599/1287183

like image 152
Michael Best Avatar answered Feb 18 '23 10:02

Michael Best