Blog

AngularJS Filters

  • (4.0)
  •   |   736 Ratings

Filters are used to format or to modify the data of an element or used along with an expression or directive (with a pipe character).

AngularJS provides quite a good number of built-in filters, and as you’ve seen earlier, building a new filter isn’t that tough either.

AngularJS filters What are they??

Here is the list of built-in AngularJS filters that one can use without even a second thought. Filters are executed when their inputs have altered in conjunction with templates. Filters can be used in conjunction with controllers, services and directives.

Without further delay, let’s get deep diving into the concepts and the usage of filters.

Accelerate Your career with AngularJS Training and become expertise in AngularJS. Enroll For Free AngularJS Training Demo!

Classification of built-in AngularJS filters:

1. String filters

format: This filter is used to format the given set of strings as per the placeholders provided

‘Hello {0}, How is {1} doing?’ | string.format : ‘Samwell Tarley’ : ‘Ser Jorah Mormont’ will result in to this string Hello Samwell Tarley, How is Ser Jorah Mormont doing?

lowercase: This filter is used to convert all the uppercased letters of a string to lowercase

‘CErSEi LANNISTer’ | string.lowercase results in cersei lannister

2. Array filters

join: This filter is used to join a given series of datatypes to a resultant single string.

[‘CERSEI’, ‘JAIME’, ‘TYRION’] | array.join:’, ’ results in CERSEI, JAIME, TYRION

reverse: This filter reverses the order of elements present in the given array.

ng-repeat=’[“CERSEI”, “JAIME”, “TYRION”] | array.reverse’ results in “TYRION”,“JAIME”,”CERSEI”

3. Math filters

max: This filter is used to find out the maximum value of the available list of numbers.

[5, 9, 4, 1] | math.max results in 9

min: This filter is used to find out the minimum value of the available list of numbers.

4. Boolean filters

YesNo: This filter is used to evaluate the Boolean expressions as a YES or a NO accordingly.

‘CERSEI’==’SANSA’ | binary.YesNo results in No

5. Debug filters

print: This filter is used to print the value bound to an element.

‘DebuggableValue’ | debug.print prints DebuggableValue

The filter Filter:

The filter Filter selects items from an array based on the criteria specified and then returns a new array as an output. The criteria for the filter Filter can be a String, Object, or a function altogether. We can optionally do a stricter comparison of the criteria from the available list of values based on the value provided.

The following example will you give you a clear idea of how this works:

AngularJS filter Filter Demo:

Name to search:
 

Result: {{mySearchArrayElements | filter:nameSearchCriteria}}

results to the following screen for us to input a certain name, as follows: and when a search criteria is entered, check how the Result attribute gets changed:

AngularJS filter

How to build our own custom AngularJS filter?

Writing a custom filter of our own is just a cake walk, but for the better good of the new AngularJS aspirants we will take it really slow. The step is just to make sure that you register a new filter factory function with your module. The basic expectation out of a custom filter function is that it should be a pure function, meaning, it should always return the exact same result given the exact same input value. AngularJS makes it very stringent on following this contract and makes it a point to execute a filter function code only when the inputs to the function are changed explicitly.

Our custom filter is going to identify the name of the day by taking a number as input (example, 1 is Monday and so on). So let’s get down to business in writing our own filter.

app.filter(‘identifyDayByANumber’, function(){

    return function(number) {

    if(number === 1) {

        return ‘Monday’

    } else if(number === 2) {

        return ‘Tuesday’

    } else if(number === 3) {

        return ‘Wednesday’

    } else if(number === 4) {

        return ‘Thursday’

    } else if(number === 5) {

        return ‘Friday’

    } else if(number === 6) {

        return ‘Saturday’

    } else if(number === 7) {

        return ‘Sunday’

    }

}

})

The filter code is just checking the number that is being passed to it and based on the number that is being passed to it, evaluates which day of the week it is. Simple isn’t it? Now let’s see how we can use this filter in practical use, shall we?

Applying the filter that we have created above as follows, results in the day just as expected. Please check this out:

{{ 6 | identifyDayByANumber }} results in Saturday

Now let’s negative test our filter that we’ve created above by passing ‘Saturday’ as input and see what happens:

{{ ‘Saturday’ | identifyDayByANumber }} results in Saturday again as the input doesn’t evaluate to a value in any of the filter conditions, hence comes the way just as it was sent to it.

Now what we can learn from the negative test that we have done above, it is a good practice to provide the proper datatype to your filter based on your requirement and if none of the conditions are met then you should remember to send the input as is without any modifications.

Checkout AngularJS Interview Questions

 

How to Unit test your filters?

Each built-in filter is covered by Unit tests and any of the filters that you create can also have unit tests as well. Running unit tests as explained earlier is very simple, run just the following commands.

npm run karma

npm run karma2

Let us write some unit tests for our filter, so that we can also see how the execution of these would work against our filter code.

describe(‘identifyDayByANumber’, function() {

    beforeEach(module(‘core’));

    it(‘should convert given number to a weekday’, inject(function(identifyDayByANumberFilter)) {

        expect(identifyDayByANumberFilter(1)).toBe(‘Monday’);

        expect(identifyDayByANumberFilter(7)).toBe(‘Sunday’);

})

);

});

As you’ve observed, while injecting a filter there is a definite need for us to suffix the filter name with ‘Filter’. For instance, our identifyDayByANumber filter is injected as identifyDayByANumberFilter.

Conclusion:

Today we have learn about AngularJS built-in filters, had a custom filter built in the form of identifying the day by a number. Building filters is the easiest job while using AngularJS but then a point to remember is that you need to keep your code clean. A point not to forget is that the sole purpose of a filter is modify / change / alter the element value and when we are unable to do that, we need to ensure that we send back the input value untouched.

Explore AngularJS Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Filters are one of the best ways to enhance your presentation of the applications, I hope that the main intent of this article is satisfied well.

 


Popular Courses in 2018

Get Updates on Tech posts, Interview & Certification questions and training schedules