Pagination with $filter for searching in AngularJS


My previous article demonstrated how to implement pagination in AngularJS, this article demonstrates how to implement pagination with $filter(searching) server.

Getting Started

In AngularJS $filter service is used to search data in a table, in this article we will implement $filter fore searching and maintain pagination. After implementing pagination logic, it is very easy to implement $filter. But need to keep in mind that the page number should display based on the search.

For example let's say there are 1000 records and after searching you got 100 records. In each page you want display 10 records, hence the number of page should be display 10 not 100.

Getting accurate page number, use $filter first before implement your pagination logic with list of collection you want display in table other wise you will get invalid search data like below image. The below code example demonstrates how to implement pagination with search option.


 <HTML ng-app = "myapp">  
       <TITLE> AngularJS Learning(Pagination with searching)</TITLE>  
       <script src=""></script>  
             var myapp=angular.module("myapp",[]);  
             myapp.filter('displayPageData', function() {  
                return function(input, start) {  
                start = +start; //parse to int  
                return input.slice(start);  
                     $scope.currentPage = 0;  
                     for (var i=1; i<=100; i++) {  
                                    if( i % 2 == 0){  
                var pageno=($filter('filter')($scope.students, $scope.searchText)).length/$scope.pageSize;  
                     return pageno;  
     return ($filter('filter')($scope.students, $scope.searchText)).length; }  
       <BODY ng-controller="myappcont">  
           <h2>Student List</h2>  
           <table border="1" style="width:60%">  
                     Search : <input type="text" placeholder="Enter to search record" ng-model="searchText"/>  
                     <tr ng-repeat="student in students|filter:searchText|displayPageData:currentPage*pageSize|limitTo:pageSize">  
        <table width="60%">  
                               <th width="10%">  
                                    <button alignment="left" ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">Previous</button>  
                               <th width="80%">{{currentPage+1}}of {{numberOfPages()| number:0}}</th>  
                               <th width="10%">  
                                    <button alignment="left" ng-disabled="currentPage >= numberOfItems()/pageSize-1" ng-click="currentPage=currentPage+1">Next</button>  


Hope this article may helpful to you, happy coding enjo...........y.

Kailash Chandra Behera

No comments:

Post a Comment