Mofizur
Mofizur

Reputation: 145

Show limited rows with knockoutjs foreach control in a table

I have an object called results in viewmodel and i am just showing that rows in my view file with foreach loop.

<table>
                    <thead>
                        <tr>
                            <th >Id</th>
                            <th >Name</th>
                        </tr>
                    </thead>
                    <tbody data-bind="foreach: result">
                        <tr>
                            <td data-bind="text: Nr"></td>
                            <td data-bind="text: Name"></td>
                        </tr>
                    </tbody>
</table>

My result object has like 300 rows but i would like to show only the first 10 rows and then add a link to load more.

could you please tell how can i achieve that. I am not wished to use knockoutJS gridview .

Thanks

Upvotes: 0

Views: 544

Answers (1)

Roy J
Roy J

Reputation: 43881

Your foreach should be bound to a computed that returns the slice of rows you want to display. You'll need an observable to store how many rows that is, and a function to increase the number.

function obj(nr, name) {
  return {
    Nr: nr,
    Name: name
  };
}

vm = {
  howmany: ko.observable(3),
  showMore: function() {
    vm.howmany(vm.howmany() + 3);
  },
  result: [
    obj(1, 'one'),
    obj(2, 'two'),
    obj(3, 'three'),
    obj(4, 'four'),
    obj(5, 'five'),
    obj(6, 'six'),
    obj(7, 'seven'),
    obj(8, 'eight'),
    obj(9, 'nine'),
    obj(10, 'one')
  ],
  sliced: ko.pureComputed(function () {
    return vm.result.slice(0, vm.howmany());
  })
};

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: sliced">
    <tr>
      <td data-bind="text: Nr"></td>
      <td data-bind="text: Name"></td>
      <td data-bind="text: Date.now()"></td>
    </tr>
  </tbody>
</table>
<button data-bind="click: showMore">Show More</button>

Upvotes: 3

Related Questions