Data-bind: {foreach: …} for multiple arrays

后端 未结 1 1560
我在风中等你
我在风中等你 2021-01-23 09:57

Is it possible to use data-bind: foreach for more than one array?
For example:

//do s
相关标签:
1条回答
  • 2021-01-23 10:43

    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>

    0 讨论(0)
提交回复
热议问题