Writting Your Own Filters In Angular JS

29 / Jan / 2014 by Sakshi Tyagi 0 comments

While using AngularJS, we come across situation in which we want to display some data in certain format or some specific condition to be applied on the data. In this case, filters comes to rescue.

We can define our custom filters and return filtered data in whichever way we want to display it.

Lets learn it through an example:

angular.module('myDemoApp', []).filter('truncate',function () {
                    return function (input, length) {
                        input = input + "";
                        if (input.length > length) {
                            var desc = input.substring(0, length);
                            return desc + "...";
                        } else {
                            return input;

Here, we have defined a filter named “truncate” which return a string concatenated with (…) if length of the string is more than parameter provided to the filter, otherwise return the same string as it is. So, we have a function with two arguments, first one is the string itself and second one is the length upto which we want to truncate the string.

Now we can simply use the filter in our html code.

<div>{{ place | truncate:8}}</div>

For example if place is “Netherlands”, it will print Netherla...

Similarly we can write our own filters according to our need.

Hope this will help :-)

Building Intuitive Frontend Interfaces with AngularJS


Leave a comment -