Monday, April 14, 2014

How to create a custom Filter with AngularJS



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

1
angular.module('yourModuleName', [])

2. Create the filter and his function

1
2
3
4
5
6
angular.module('yourModuleName', [])
    .filter('yourFilterName', function () {
        return function () {
            return;
        };
    });

3. Register the module in the application

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

Example: Truncate Filter

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
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.

No comments:

Post a Comment