Saturday, May 16, 2015

Client side pagination using AngularJS

The great advantage of client side pagination is , we need not go to server for each page. General client side pagination is nice when the amount of data is not very much. The reason is , It takes all data from server and render page wise.

There are various techniques to implement pagination in client side. In this article, we will use AngularJS to implement client side pagination.

var todos = angular.module('travel', ['ui.bootstrap']);

todos.controller('TodoController', function ($scope, $http) {
    $scope.filteredTodos = []
   , $scope.currentPage = 1
   , $scope.numPerPage = 5
   , $scope.maxSize = 5;

    $scope.makeTodos = function () {
        $scope.todos = [];
       
        $http.get('/Hotel/ReturnHotels').then(function (response) {
            $scope.todos = response.data.Establishments;

            $scope.$watch('currentPage + numPerPage', function () {
                var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                , end = begin + $scope.numPerPage;
                $scope.filteredTodos = $scope.todos.slice(begin, end);
            });
        });
    };

    $scope.makeTodos();
});


Here is controller to get data and to implement pagination. Here we will use bootstrap ui framework to creat pagination.

Please have a look that we have injected ‘ui.bootstrap’ module in module of angular. $scope.$watch will trigger as soon as data will get change for ‘currentPage and PageNumber’ variable. That is needed, to show updated data when user will navigate page to page.

Here is client code

<!DOCTYPE html>
<html ng-app="travel">
<head>
    <link data-require="bootstrap-css" data-semver="3.3.1" rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
    <script data-require="angular.js" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
    <script data-require="ui-bootstrap" data-semver="0.12.1" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="~/js/app.js"></script>
</head>

<body ng-controller="TodoController">
    <div>
            <ul>
                <li ng-repeat="todo in todos">{{todo.Name}}</li>
            </ul>

            <pagination ng-model="currentPage"
                        total-items="todos.length"
                        max-size="maxSize"
                        boundary-links="true">
            </pagination>
    </div>
   
</body>

</html>


Once we run the application we will see data with pagination.


Please keep in mind that client side pagination is good when data is not in high volume because it will pull all data at a time.

If there is really huge data to display it’s always good to implement server side pagination. 

2 comments: