I've included a code snippet which demonstrates the problem I'm trying to solve. I'm trying to build a two column layout based upon the data within an observableArray
. I've tried using the Knockout if
bindings, but that doesn't work well within the foreach
. This seems like it should be very simple, but for some reason I haven't been able to figure out how to make this work within the realm of Knockout.
function ViewModel() { var self = this; self.People = ko.observableArray([1, 2, 3, 4, 5]); } var viewModel = new ViewModel(); ko.applyBindings(viewModel);
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <h4>Current</h4> <div class="row"> <div class="col-xs-12" data-bind="foreach: People"> <p data-bind="text: $data"></p> </div> </div> <h4>Desired</h4> <div class="row"> <div class="col-xs-12"> <div class="row"> <div class="col-xs-6">1</div> <div class="col-xs-6">2</div> </div> <div class="row"> <div class="col-xs-6">3</div> <div class="col-xs-6">4</div> </div> <div class="row"> <div class="col-xs-6">5</div> </div> </div> </div>
Try that:
<div class="row">
<div class="col-xs-12" data-bind="foreach: People">
<!-- ko if: $index() % 2 == 0 -->
<div class="row">
<div class="col-xs-6" data-bind="text: $parent.People()[$index()]"></div>
<div class="col-xs-6" data-bind="text: $parent.People()[$index()+1]"></div>
</div>
<!-- /ko -->
</div>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.