Using Angular - Filter and Sort a Table

Using Angular Filter and Sort a Table

In this post, we’ll be looking at a way to filter and sort our data in the table. When building Angular applications, one of the cornerstones we will use is ng-repeat. Showing data is something that we do in applications like when we show a table of users or whatever other data we need to show our users. This is a common feature that is always useful so let’s look at what we’ll be building and dive right into the code.

This demo will allow us to:
  • Show a table of data (ng-repeat[1])
  • Sort by ascending or descending columns (orderBy[2])
  • Filter by using a search field (filter[3])

These three common functions in Angular let’s us implement these features in a very simple way. 
We'll create a simple module with one controller where we define a few variables and the list of data we’ll show to our users.

script:

We have created various variables for sorting and searching, and also a list of data's to be displayed.

html:

We have mapped the Angular module and Angular controller in the HTML. We are also using an ngRepeat to loop over the products in our $scope.products array we created in our Angular module.

Sorting the Table
The sorting feature is implemented by using two of the variables that we created earlier (
$scope.sortType and $scope.sortReverse). We will also be using the Angular orderBy filter. Basically, applying a combination of sortType and sortReverse variables to an orderBy clause in our ng-repeat will sort the table.

In order to sort column by clicking the thead section, we'll be adding ng-click to adjust the sortType variable. Now as you click the links across your table headers, you’ll see your table sorted since we are setting the sortType variable using ng-click.

Changing the Sort Order
The orderBy filter arguments offer a third parameter for reverse. We just have to pass in true or false to change the sort order. Currently we have it set to false since we defined that as one of the variables earlier ($scope.sortReverse). The way we will give users the option to reverse the sort is to add sortReverse = !sortReverse in the ng-click of our table headers. This will change the order if users click the link.

Filtering the Table
Filtering data in ng-repeat is fairly easy since Angular also comes with the filter module. There are only two things we need to do here: create the form and apply the form variable to the ng-repeat. We need to define a ng-model, with that variable we need to apply it to our ng-repeat. Filter will now be applied to the table.

Using some built in Angular tools like ngRepeat, orderBy, filter, ngClick, and ngShow, we’ve been able to build a clean and fast table of data.


References:
[2] orderBy
[3] filter

Comments

Popular posts from this blog

Typeahead using Angular JS and Bootstrap

AngularJS Checkbox Select

Sorting DIV's using jQuery