I have the following table where I'm attempting to loop through coverage lines. I would like 2 columns with a different line in each, however my code duplicates the same coverage in each column. Any suggesions on how to get a 2 column layout without the repetition? Which element should my foreach binding go on? Thanks.
<table class="coverage-table" data-bind="foreach: $root.clientVM.CustomCoverageLines">
<tr>
<td>
<input type="checkbox" data-bind="checked: Checked" />
<label>
<span data-bind="text: $data.Description"></span>
</label>
</td>
<td>
<input type="checkbox" data-bind="checked: Checked" />
<label>
<span data-bind="text: $data.Description"></span>
</label>
</td>
</tr>
</table>
You could add a computed property to your model that structures the data in the way that you want. See this JSFiddle for an example: http://jsfiddle.net/6gvtz51g/. An advantage to this approach is that you can specify a different row size if you would like.
<table data-bind="foreach: coverageLineRows">
<tr data-bind="foreach: $data">
<td>
<span data-bind="text: $data"></span>
</td>
</tr>
</table>
function ViewModel () {
var self = this;
self.coverageLines = ko.observableArray([
'Medical',
'Dental',
'Vision',
'Life'
]);
self.coverageLineRowSize = ko.observable(2);
self.coverageLineRows = ko.computed(function () {
var rows = [];
var i = 0;
var lines = self.coverageLines();
var size = self.coverageLineRowSize();
while (i < lines.length) {
rows.push(lines.slice(i, i += size));
}
return rows;
});
}
ko.applyBindings(new ViewModel());
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