Custom Filters
Chainable filters for formatting values in templates.
Code
angular.module('filtersApp', [])
.filter('capitalize', function() {
return function(input) {
if (!input) return '';
input = input.toLowerCase();
return input.charAt(0).toUpperCase() + input.slice(1);
};
})
.filter('truncate', function() {
return function(input, length) {
if (!input) return '';
return input.length > length
? input.slice(0, length) + '...'
: input;
};
})
.filter('range', function() {
return function(input, total) {
for (let i = 0; i < total; i++) input.push(i);
return input;
};
});
<!-- Usage -->
<p>{{ 'hello world' | capitalize }}</p> <!-- Hello world -->
<p>{{ 'Some long text here' | truncate:8 }}</p> <!-- Some lon... -->
<li ng-repeat="n in [] | range:5">{{ n }}</li> <!-- 0 1 2 3 4 -->Explanation
Filters format data in templates via the pipe syntax, accepting arguments after a colon. Each filter is a factory returning a transform function; chain multiple filters with successive pipes (value | filterA | filterB). Built-in filters include currency, date, orderBy, and filter, while custom filters plug into the same pipeline.
More AngularJS Snippets
Module & Controller
Define a module and a controller with scope methods.
Scope Inheritance
Prototypal scope inheritance between parent and child controllers.
Custom Directives
Attribute directive and element directive with isolated scope.
Services & Factories
Factory and service singletons for shared state and logic.
Routing (ngRoute)
Configure routes with templates, controllers, and resolve guards.
Forms & Validation
Form with required, minlength, email validation, and disabled submit.