Hey guys,
In the previous post we have learned How to create User Registration & Login application.
This is a follow up to my earlier posts on Angular JS. In this tutorial I’ll show you how to make your lists/tables rich with features like Sorting, Filtering, and Pagination.
We use lists and tables to display data in numerous Angular JS applications. But sometimes, you need more than just displaying data, like when you want to present data in a manageable way. That’s where you can put the above mentioned features to the best use.
We’ll cover each of these features one at a time so you have a better understanding of them.
You can also download a zipped version of the source code used from this link
A video demo of this tutorial is available here Live Demo
As a first step, we’ll set up a new Angular JS application called ‘GridApp’ with a basic controller called ‘GridController’ which we’ll be using throughout this tutorial. I’ve included the following files in the index.html file:
Your index.html should look similar to the code below.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>folio3 | Filtering, Sorting, and Paging in Angular JS</title> <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link href="css/main.css" rel="stylesheet" type="text/css"> <script src="js/angular.min.js"></script> <script src="js/app.js"></script> <script src="js/controllers/grid.js"></script> </head> <body ng-app="GridApp"> <div ng-controller="GridController" class="container"> <h2>Filtering, Sorting, and Paging in Angular JS</h2> <hr> <div class="grid"> </div> </div> </body> </html>
Our app.js file will only contains app initialization code, which is:
(function(){ var app = angular.module('GridApp', []); })();
Now that we’ve set up our application, let’s move to adding and displaying some data. In this tutorial, we’ll be using random JSON data that I’ll be adding to the ‘grid.js’ file. Alternatively, you can also use an Ajax request (using $http) to fetch the data to display.
(function(){ var app = angular.module('GridApp', []); app.controller('GridController', ['$scope', function($scope){ scope = $scope; scope.people = [ { "id": "5715c444e236108e544c1b86", "age": 38, "name": "Sparks Moreno", "gender": "male", "company": "ENERSOL" }, .., .., { "id": "5715c44453fed3230c8cae0b", "age": 40, "name": "Donovan Herman", "gender": "male", "company": "ROCKABYE" } ]; }]); })();
Next, we’ll use the ng-repeat directive to display this data in a table format. I’ve added some table styles in the css (as shown below). You should do the same.
<div class="grid"> <table> <tr> <td>Name</td> <td>Age</td> <td>Gender</td> <td>Company></td> </tr> <tr ng-repeat="person in people"> <td>{{person.name}}</td> <td>{{person.age}}</td> <td>{{person.gender}}</td> <td>{{person.company}}</td> </tr> </table> </div>
Now, if you run your application in a browser, you’ll see your data being displayed nicely in a table (depending on how you styled it).
Filtering data in Angular JS is also pretty easy. Since Angular JS comes with a number of amazing filters that you can use to transform data. Let’s look at these in detail below.
Before we add any filtering code though, let’s first add an input search field in our index.html file, which we’ll be binding to our controller data using the ng-model directive. To do so, just add the following markup above the markup for your “grid” div (as shown below).
<div class="form-group"> <label class="sr-only">Search:</label> <input class="form-control" type="text" ng-model="queryText" placeholder="Search"> </div> <h3 ng-show="queryText">Showing results for: {{queryText}}</h3>
You’ll be surprised to see how easily you can filter your data using this method. In the previous step, we used the ng-repeat directive to iterate through our data and display it. In this case, we’ll apply our filter to sort the data. Update the above markup as depicted below.
ng-repeat=”person in people | filter: queryText”
What we’ve done in the code snippet above, is that we’ve applied a data filter (yes, it’s a data filter that is named filter). Filters in Angular JS can be applied by using the | (pipe) character followed by the filter name. The filter used in this case, searches through our data and returns a subset of matched items. The beauty of Angular JS data-binding is that whenever you type anything in the search field, the view will automatically be updated with the new results. No bloated DOM manipulation code is necessary for that in Angular JS.
To learn more about Angular JS filters, head on over to this link. https://code.angularjs.org/1.5.5/docs/guide/filter
Now, let’s look at data sorting in Angular JS. Angular JS also offers a pre-defined filter that can help you order and sort data pretty easily. This filter takes just two arguments:
Let’s look at how we can use this sorting filter in Angular JS. Before we apply this filter though, let’s add some basic sort functionality in our controller (grid.js), as shown below.
scope.sortKey = 'name'; scope.sortReverse = false; scope.sort = function(key){ scope.sortReverse = (scope.sortKey == key) ? !scope.sortReverse : scope.sortReverse; scope.sortKey = key; }
In the above code snippet, we’ve added default sorting configuration and a function that takes a key as an argument. This function also toggles the sorting order if it’s called twice with the same key passed. Now you just need to apply the orderByfilter and update your table heading markup to call this function upon ng-click (as shown below).
<table> <tr> <td ng-click="sort('name')">Name <span class="glyphicon sort-icon" ng-show="sortKey=='name'" ng-class="{'glyphicon-chevron-up':sortReverse,'glyphicon-chevron-down':!sortReverse}"></span> </td> <td ng-click="sort('age')">Age <span class="glyphicon sort-icon" ng-show="sortKey=='age'" ng-class="{'glyphicon-chevron-up':sortReverse,'glyphicon-chevron-down':!sortReverse}"></span> </td> <td ng-click="sort('gender')">Gender <span class="glyphicon sort-icon" ng-show="sortKey=='gender'" ng-class="{'glyphicon-chevron-up':sortReverse,'glyphicon-chevron-down':!sortReverse}"></span> </td> <td ng-click="sort('company')">Company <span class="glyphicon sort-icon" ng-show="sortKey=='company'" ng-class="{'glyphicon-chevron-up':sortReverse,'glyphicon-chevron-down':!sortReverse}"></span> </td> </tr> <tr ng-repeat="person in people| filter: queryText | orderBy:sortKey:sortReverse"> … </tr>
Please note that in above code snippet, I’ve added glyphicons to indicate the current sort order. Now, just run the application in a browser to see sorting in action.
The last and final chapter in this tutorial is about using pagination in Angular JS. You might be thinking that there’s a built-in pagination control provided by Angular JS that can speed thing ups in this area too, similar to what we saw for filters and sorting, etc.. Sadly no, this is not the case when it comes to pagination. Angular JS doesn’t come with pagination support out-of-the-box. So what do you do? Do you write the whole pagination logic by yourself? The answer is no, you don’t need to reinvent the wheel since there are quite a few libraries available for it, unless you’re planning on inventing a very special wheel for pagination.
The pagination library I’ll be is the dirPaginate. The reason I chose this library is because it offers an excellent set of features for pagination in Angular JS, and also because it’s really easy to add in any Angular application. Let’s look at this library in detail.
The first thing you need to do is add the dirPaginate library to our project. You can install it with Bower, or npm, or just download it manually from this link.
Bower: bower install angular-utils-pagination
npm: npm install angular-utils-pagination
Next, include the link to the dirPagination.js file to your index.html file. Then all you have to do is add the ‘angularUtils.directives.dirPagination’ module in the controller file. The updated file should appear as shown below:
var app = angular.module('GridApp', ['angularUtils.directives.dirPagination']); ..
Also, make sure to add a scope variable for the number of items you want to display per page (as depicted below).
scope.itemsPerPage = 10;
To make use of dirPaginate, you have to replace your ng-repeat directive with the dir-paginate directive. You don’t have to worry about this breaking any current functionality though. All the filters you’ve used will work just fine.
Another thing you need to add here is a dirPaginate filter, which will restrict the items shown per page. So update your markup to:
<tr dir-paginate="person in people | filter: queryText | orderBy:sortKey:sortReverse | itemsPerPage: itemsPerPage" pagination-id="people"> <td>{{person.name}}</td> <td>{{person.age}}</td> <td>{{person.gender}}</td> <td>{{person.company}}</td> </tr>
The thing to keep in mind here is that the itemsPerPagefilter should be applied after all other filters.
Once you’ve done all that, there’s just one more thing left to add, and that is the pagination links. To include those, add the following code right after your grid:
<dir-pagination-controls pagination-id="people" class="pull-right"></dir-pagination-controls>
This will automatically display/hide the pagination links based on your data. Please do remember that the pagination-idmust match, in order for the links and pagination to work.
You can read more about the dirPaginate library at the link below. https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
And that’s it. If you’ve performed the steps above correct, the final screenshot of the application will look like this.
In this tutorial, I showed you how to display data in a tabular format and implement filtering, sorting, and paging functionality in Angular JS. These features provide ease of use when working with Angular JS, especially when you are working with a large quantity of tabular data. I would recommend that you go through all the links given in this post, to get a better understanding of all these features.
In the next tutorial we will learn How to Upload File in Angular JS
USA408 365 4638
1301 Shoreway Road, Suite 160,
Belmont, CA 94002
Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.
Tel:
+1 408 365 4638
Support:
+1 (408) 512 1812
COMMENTS ()
Tweet