In AngularJS, the $filter service is used to search the data in a table. In this blog, we will implement $filter for searching and maintaining the pagination. After implementing the pagination logic, it is very easy to implement the $filter service. But we need to keep in mind that the page number should be displayed based on the search.
For example, let's say there are 1000 records and after searching, you got 100 records. On each page, you want to display 10 records, hence the number of pages should be displayed 10, not 100.
To get the accurate page number, use $filter first, before implementing your pagination logic with the list of the collection that you want to display in the table. Otherwise, you will get an invalid search data like in the 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="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
- <script>
- var myapp=angular.module("myapp",[]);
- myapp.filter('displayPageData', function() {
- return function(input, start) {
- start = +start; //parse to int
- return input.slice(start);
- }
- });
- myapp.controller("myappcont",function($scope,$filter){
- $scope.currentPage = 0;
- $scope.searchText='';
- $scope.pageSize=10;
- $scope.students=[];
- for (var i=1; i<=100; i++) {
- if( i % 2 == 0){
- $scope.students.push({Name:"Student"+i,Gender:"Male",Class:i+"Std",Section:"A"});
- }
- else{
- $scope.students.push({Name:"Student"+i,Gender:"Female",Class:i+"Std",Section:"B"});
- }
- }
- $scope.numberOfPages=function(){
- var pageno=($filter('filter')($scope.students, $scope.searchText)).length/$scope.pageSize;
- if(pageno==0){
- pageno++;
- }
- return pageno;
- }
- $scope.numberOfItems=function(){
- return ($filter('filter')($scope.students, $scope.searchText)).length; }
- });
- </script>
- <BODY ng-controller="myappcont">
- <h2>Student List</h2>
- <hr/>
- <table border="1" style="width:60%">
- <caption>
- Search : <input type="text" placeholder="Enter to search record" ng-model="searchText"/>
- </caption>
- <thead>
- <tr>
- <th>Name</th>
- <th>Gender</th>
- <th>Class</th>
- <th>Section</th>
- </tr>
- </thead>
- <tbody>
- <tr ng-repeat="student in students|filter:searchText|displayPageData:currentPage*pageSize|limitTo:pageSize">
- <td>{{student.Name}}</td>
- <td>{{student.Gender}}</td>
- <td>{{student.Class}}</td>
- <td>{{student.Section}}</td>
- </tr>
- </tbody>
- </table>
- <table width="60%">
- <tr>
- <th width="10%">
- <button alignment="left" ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">Previous</button>
- </th>
- <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>
- </th>
- </tr>
- </table>
- </BODY>
- </HTML>