Vladimir
Vladimir

Reputation: 351

knockoutjs load inside foreach

I have foreach binding with knockoutjs.

<tbody data-bind="foreach: contracts">
<tr>
<td data-bind="text: Number"></td>
<td data-bind="text: BusinessName"></td>
<td> <div> I need load content to this div with ajax, url depends on $data.id value </div> </td>
</tr>
</tbody>

as you see, there is div inside last td, I need load content to this div with $("div").load("/Controller/Action/$data.Id") where $data is element from foreach cycle. Can someone advise? Thank you.

Upvotes: 0

Views: 165

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

You should add a property to your view model that you can populate via an ajax call. Something like this:

function Contract(number, name) {
  var self = this;
  self.number = ko.observable(number);
  self.businessName = ko.observable(name);
  self.content = ko.observable();    // note: you could provide a default value
                                     // while loading if you want, or better might
                                     // be an "isLoading" observable

  // load your ajax content:
  // eg. $.ajax(yourUrl, { data: ....
  // your callback would actually populate self.content
  // Just faking it here with a timeout:
  setTimeout(function() {
    self.content("foo");
  }, 1000);
}

function ViewModel() {
  var self = this;
  self.contracts = ko.observableArray();
}

var vm = new ViewModel();
vm.contracts.push(new Contract("1", "2"));
vm.contracts.push(new Contract("a", "b"));
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
<tbody data-bind="foreach: contracts">
  <tr>
    <td data-bind="text: number"></td>
    <td data-bind="text: businessName"></td>
    <td>
      <div data-bind="text: content"></div>
    </td>
  </tr>
</tbody>
  </table>

Upvotes: 1

Related Questions