How to create a custom Filter with AngularJS v1.0

A few days ago I needed to create a custom filter to truncate a piece of text with a specific length and with a custom ending, something like this: "This is an Examp...".

Before I continue, I want to refer that AngularJS is on version 1.0. At this version the documentation is not yet completed.

The creation of custom filters only needs three things:

  1. Create the module
  2. Create the filter and his function
  3. Register the module in the application

1. Create the module

angular.module('yourModuleName', [])

2. Create the filter and his function

angular.module('yourModuleName', [])
    .filter('yourFilterName', function () {
        return function () {
            return;
        };
    });

3. Register the module in the application

angular.module('yourAppName', ['yourModuleName']);

Example: Truncate Filter

angular.module('filters', []).
    filter('truncate', function () {
        return function (text, length, end) {
            if (isNaN(length))
                length = 10;
            if (end === undefined)
                end = "...";
            if (text.length <= length || text.length - end.length <= length) {
                return text;
            }
            else {
                return String(text).substring(0, length-end.length) + end;
            }
        };
    });

You can see this example on this gist and run it on jsfiddle.

Note: This can not be the best practice implementation, but was the result I achieved and solved my problem.

comments powered by Disqus