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.
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.
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/
<!-- 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 -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With