Subscribe

Search and OrderBy Filter in AngularJS

In this tutorial we have demonstrated a very cool feature of AngularJS which can save you hours of coding and googling for one specific functionality of filtering out data in a list or table of data. Filter feature of AngularJS does the trick, read on to know how.

In this short tutorial we will solve a very typical problem which could take too much coding efforts to do by casual JavaScript or JQuery. Often we come across the situation where we need to provide our client a long list of stuff in a table, and customer wants to filter out the information quickly. Thus we opt for key press events based JQuery to filter out things and show only relevant or matching stuff, here as a developer it may take too much of valuable time. Thus Angular has come up with a very easy phenomenon of filter. Whenever you create a table of data from the JSON response coming from a web service use this filter and make your way smooth.

You can use whichever TextEditor or IDE you like, and Download AngularJS library or use CDN from here.

Before Proceeding with the tutorial we warn you that this is not for absolute beginner, we assume you atleast know the basics of AngularJS because we will only focus on key point which is filter.

We are using a scenario with a static JSON array with properties title and category of websites. We will create a table and search box which filter the result in table and only displays matching result. The JSON array looks like this:

In our code we have created an HTML page with angular app by the name of searchDemoApp and controller searchDemoController. We specify the JSON array within the scope of this controller of ours. After that we use ng-repeat to print out this JSON data in form of a data table, code looks like this.

Please note that while using ng-repeat we have applied a filter "lookup" to this iteration of the data, this filter is binding the table data with a model named "lookup"(you can give it whatever name you like). After that we bind this model with a text field which acts as the search field, shown in code below.

Cool Tip

you can use orderBy:'parameter' filter alone or along with other filter in ng-repeat to order the data in specific order, for example ng-repeat="something in manythings |filter:search | orderBy:'title'".