ArticleZip > Pagination On A List Using Ng Repeat

Pagination On A List Using Ng Repeat

When you're dealing with a long list of items in AngularJS, it can quickly become overwhelming for users if they have to scroll through everything at once. That's where pagination comes in to save the day! In this article, we'll walk you through how to add pagination to a list using `ng-repeat` in AngularJS.

First things first, let's make sure you have AngularJS set up in your project. If you don't already have it installed, you can include it via a CDN link in your HTML file. Once that's done, you're ready to start implementing pagination.

To begin, you'll need to have a list of items that you want to display paginated. Let's say you have an array of objects called `items`, and you want to display 10 items per page. You can start by setting up your controller with the following code snippet:

Javascript

$scope.items = [
  { name: 'Item 1' },
  { name: 'Item 2' },
  // Add more items as needed
];

$scope.currentPage = 1;
$scope.itemsPerPage = 10;

$scope.totalPages = Math.ceil($scope.items.length / $scope.itemsPerPage);

$scope.paginate = function() {
  return $filter('limitTo')($scope.items, $scope.itemsPerPage, ($scope.currentPage - 1) * $scope.itemsPerPage);
};

In the code above, we define the `items` array, set the `currentPage` to 1, specify `itemsPerPage` as 10 items per page, calculate the `totalPages` based on the total number of items and items per page. The `paginate` function is responsible for returning the items to display based on the current page.

Next, let's set up the HTML template to display the paginated list. Here's an example of how you can achieve this:

Html

<div>
  <p>{{ item.name }}</p>
</div>

<button>{{ $index + 1 }}</button>

In the HTML code snippet above, we use the `ng-repeat` directive to iterate over the items returned by the `paginate` function. Each item is displayed within a `

` element. We also create a set of buttons to represent the pagination controls. By clicking on each button, the `currentPage` is updated accordingly, and the list is updated based on the new page.

And there you have it – a simple way to implement pagination on a list using `ng-repeat` in AngularJS. Feel free to customize the number of items per page, the styling of the pagination controls, and any additional features you'd like to include. Pagination is a great way to enhance user experience when dealing with large datasets, so have fun implementing it in your projects!

×