Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render collection in 2 columns

Tags:

knockout.js

Currently I have:

<div data-bind="foreach: list">
</div>

And need:

<div data-bind="foreach: /* 1st half of the list */">
</div>
<div data-bind="foreach: /* 2nd half of the list */">
</div>

It would be great to avoid using 2 separate observables or computed.

like image 886
Sergey Metlov Avatar asked Mar 05 '13 08:03

Sergey Metlov


3 Answers

You can use the array slice method to create the two collections:

<div data-bind="foreach: list.slice(0, list.length / 2) ">
    <span data-bind="text: $data" />
</div>
<div data-bind="foreach: list.slice(list.length / 2)">
    <span data-bind="text: $data" />
</div>

If you have an observable array you need to slightly modify your bindings:

<div data-bind="foreach: list.slice(0,list().length / 2) ">
    <span data-bind="text: $data"/>
</div>
<div data-bind="foreach: list.slice(list().length / 2)">
    <span data-bind="text: $data"/>
</div>

Demo JSFiddle.

like image 104
nemesv Avatar answered Oct 23 '22 15:10

nemesv


You could just use mod 2, like this:

<div data-bind="foreach: list">
    <!--ko if: $index() % 2 == 0 -->
    <div class="row">
        <div class="col-md-6">
            <span data-bind="text: $data"></span>
        </div>
        <div data-bind="with: $parent.list()[$index()+1]" class="col-md-6">
            <span data-bind="text: $data"></span>
        </div>
    </div>
    <!--/ko-->
</div>

Fiddle: http://jsfiddle.net/robgallen/1728389j/

like image 32
Space Monkey Avatar answered Oct 23 '22 14:10

Space Monkey


A safe and clean example of using an observable array

<!-- ko with: myObservableArray -->
    <div data-bind="foreach: $data.slice(0, $data.length / 2)">
        <span data-bind="text: $data"/>
    </div>
    <div data-bind="foreach: $data.slice($data.length / 2)">
        <span data-bind="text: $data"/>
    </div>
<!-- /ko -->
like image 20
Mike Rapadas Avatar answered Oct 23 '22 14:10

Mike Rapadas