Is it possible to use data-bind: foreach
for more than one array?
For example:
//do s
I don't think there is any official way of doing so, but a workaround would be, to use $index
along with foreach
on the longer array. Something like this:
var model = function() {
var self = this;
self.arr1 = ko.observableArray([1,2,3, 5, 6]);
self.arr2 = ko.observableArray([1,2,3,4]);
}
ko.applyBindings(new model());
span {
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<br/>
<div data-bind="foreach: (arr1().length > arr2().length ? arr1 : arr2)">
Index:
<span data-bind="text: $index"></span>,
Array 1:
<span data-bind="text: $root.arr1()[$index()]"></span>,
Array 2:
<span data-bind="text: $root.arr2()[$index()]"></span>,
Longer array:
<span data-bind="text: $data"></span>,
Shorter array:
<span data-bind="text: ($root.arr1().length < $root.arr2().length ? $root.arr1()[$index()] : $root.arr2()[$index()])"></span>
<br/>
</div>