How to make pagination using AngularJS? Use an HTML table element with the ng-repeat
directive to render only the items for the current page from JSON file. All the pagination logic should be handled in a custom filter firstPage
and controller implementation.
- Load data from JSON or any other files.
- Create a custom filter
firstPage
to display first five datas. - Create two button for 'Previous' and 'Next' navigation.
- Display current page and total page number.
HTML
<div ng-app="" ng-controller="githubController"> <table border="0" cellspacing="0" cellpadding="15"> <tr> <th width="23%">ID</th> <th>Name</th> </tr> <tr ng-repeat="x in names | firstPage:currentPage*pageSize | limitTo:pageSize"> <td>{{ x.id }}</td> <td>{{ x.name }}</td> </tr> <tr> <td>ID</td> <td>Name</td> </tr> </table>
<div class="pagination"> <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1"><</button> <span>{{currentPage+1}}/{{numberOfPages()}}</span> <button ng-disabled="currentPage >= names.length/pageSize - 1" ng-click="currentPage=currentPage+1">></button> </div>
</div>
CSS
*{ font-family: Arial; font-size:12px; } table{ text-align:left; width:100%; border-collapse: collapse; } table td{ border: 1px solid #C7C7C7; } table th{ background: #C7C7C7; color: #FFF; font-size: 13px; } .pagination{ margin: 20px 0; text-align: center; } .pagination button{ font-size: 24px; border-radius: 50%; border: 0; width: 30px; height: 30px; font-weight: normal; color: #FFF; cursor: pointer; display: inline-block; background: #C7C7C7; text-align: center; } .pagination button:focus{ outline:none; } .pagination span{ display: inline-block; margin: 0 0 10px 0; vertical-align: middle; } button:disabled { background: #ddd; cursor: default; } .credit{ background: #eee; padding: 10px; line-height: 180%; } .credit p{ margin: 0; }
JavaScript
var app=angular.module('myApp', []); function githubController($scope,$http) { $http.get("https://api.github.com/users/mralexgray/repos") .success(function(response) {$scope.names = response;}); $scope.currentPage = 0; $scope.pageSize = 5; $scope.numberOfPages=function(){ return Math.ceil($scope.names.length/$scope.pageSize); } } //startFrom filter app.filter('firstPage', function() { return function(input, start) { start = +start; return input.slice(start); } });
Include above CSS, JS and AngularJS CDN in HTML
<head> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js"></script> <!-- AngularJS --> <script type="text/javascript" src="custom.js"></script> <!-- Link custom JS --> <link rel="stylesheet" type="text/css" href="style.css"> <!-- Link custom style --> </script> </head>
Try below one sample basic single page application example.
JSON data with pagination
- shanidkv's blog
- Log in to post comments