Home » AngularJS13 July 2017

AngularJS: Search & Sort Data

This article shows how you can search and sort data using AngularJS 1.x.

We will be using code from previous article example. Our code contains country & their capitals name as an array and we display them using ng-repeat directive in HTML view.

This is our example code from previous article:

Now, we modify the code to add search and sort feature/filter on the displayed data.

First, let’s add search feature to the example code. As you can see in the below code, we have added an input text field for search. This search input field uses ng-model directive which binds the value of the search field to a variable with the same name. We can then use the search variable as filter in the ng-repeat directive.

Here’s the full code:

Now, we add sorting feature or filter to the country-capital data. When we click on the Country or Capital title, the country or capital list is sorted alphabetically.

In the above code, we have used two model variables $scope.orderByField and $scope.reverse. And, then while using ng-repeat directive, we use the orderByField variable to orderBy data.

We have also added href link to Country & Capital title. In the “a href” element, we have used ng-click directive. This directive changes the model variable orderByField so that when Country is clicked, the data is sorted by country and when Capital title is clicked then the data is sorted by capital name. Here, reverse variable is used to sort data in reverse order when the country or capital title is clicked second time.

Hope this helps. Thanks.


Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed