Monday, July 7, 2014

Filters in AngularJS

Filters in AngularJS are used to modify output or format it in required format to be displayed to user.
Angular provide some out of the box filters and it is easy to create our own filter (custom filter).

Filters can be applied to expressions in view templates using the following syntax:
{{ expression | filter }}
 E.g. Following markup formats salary using currency filter.. If salary is 20000 then after applying currency filter result would be #20000.00…In below snipped if we don’t provide currency symbol then default is ‘$’
<div>{{ employeedetails.salary | currency : '#'}}</div>

We can do chaining of filters, means filter can be applied on result of another filter.
{{ expression | filter1 | filter2 | filter3 |... }}

Filter also could have parameters and if it has parameters then those are passed like shown below
{{ expression | filter:parameter1:parameter2:... }}

Creating custom filter

Requirement:  Suppose we have employee designations stored as short forms and we want to show them in full form then we will write a filter which will return full forms for the given short forms.

  • Create a filter function on a new module because it is said to be the best practice to define filters inside new module than the existing main application module.

angular.module('myFilterModule', []).filter('DesignationFilter', function () {
    return function (inputVal) {
                switch (inputVal) {
                    case 'TA':
                        return 'Trainee Analyst';
                    case 'JA':
                        return 'Junior Analyst';
                    case 'SA':
                        return 'Senior Analyst';
                    case 'TL':
                        return 'Team Lead';
                        return 'Analyst';

Here myFilterModule is new module where we have defined our custom filter named ‘DesignationFilter’.

  • Add dependency of this new filter module in our main application module.

var demoApp = angular.module('demoApp', ['ngSanitize', 'myFilterModule']);

  • Use the filter inside expression syntax.

<div>{{employeedetails.designation | DesignationFilter}}</div>

You can Download code here for this article.

No comments:

Post a Comment