0

I have a page, containing a lot of items (observablearray), so I've created a paging system. (Well, not created myself, but copied from here How to handle pagination with Knockout ;) )

I want to show the individual buttons per page. Something like:

<  1 2 3 4  >

I have the "totalPages" property, but how can I use that in on the frontend?

How can I loop through a knockout int-variable and create links to a function with that same int?

I was hoping something like this:

<ul data-bind="foreach: totalPages">
    <li><a href="#" data-bind="text: $index, click: pageNumber($index)"></li>
</ul>

but that doesn't work.

Cryothic
  • 771
  • 7
  • 18

1 Answers1

0

You could use Array.from() to create an empty array and use it in foreach. Add a wrapper for the click function to get the $index() + 1 as a parameter:

const viewModel = {
  totalPages: ko.observable(4),
  pageNumber: n => console.log(n)
}

ko.applyBindings(viewModel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: Array.from({ length: totalPages() })">
    <li>
      <a href="#" data-bind="text: $index() + 1, click: () => $parent.pageNumber($index() + 1)"></a>
    </li>
</ul>
adiga
  • 34,372
  • 9
  • 61
  • 83