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:
- Create the module
- Create the filter and his function
- Register the module in the application
1. Create the module
{{< highlight javascript >}} angular.module('yourModuleName', []) {{< / highlight >}}2. Create the filter and his function
{{< highlight javascript >}} angular.module('yourModuleName', []) .filter('yourFilterName', function () { return function () { return; }; }); {{< / highlight >}}3. Register the module in the application
{{< highlight javascript >}} angular.module('yourAppName', ['yourModuleName']); {{< / highlight >}}Example: Truncate Filter
{{< highlight javascript >}} 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; } }; }); {{< / highlight >}}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.