Last Updated: September 09, 2019
·
2.174K
· gerardsans

Angular - how to $inject a filter

AngularJs Meetup South London Collection | this article

Filters are very handy to format data displayed to the user. Common use cases are currency, dates and numbers. Other less common filters are: uppercase, lowercase, limitTo, orderBy and json.

Inject a filter

var $filter = angular.injector(['ng', 'app']).get('$filter');

Common filters

console.log( $filter('currency')(2000) ); // $2,000.00
console.log( $filter('date')(new Date(), 'yyyy') ); // 2014
console.log( $filter('number')(1/3, 2) ); // 0.33

console.log( $filter('uppercase')("Hello") ); // HELLO
console.log( $filter('lowercase')("HELLO") ); // hello
console.log( $filter('limitTo')([1,2,3], 2) ); // [1,2]
console.log( $filter('limitTo')([1,2,3], -2) ); // [2,3]
console.log( $filter('limitTo')("Hello", 2) ); // He
console.log( $filter('limitTo')("Hello", -2) ); // lo

console.log( $filter('orderBy')([{id:1},{id:2},{id:3}], "-id") ); 
// [{id:3}, {id:2}, {id:1}]

console.log( $filter('json')({a:1}) ); // { "a" : 1 }

Basic filter usage

HTML: <span>{{ employee.name | uppercase }}</span>
Angular Expression: <span ng-bind="employee.name | uppercase"></span>
Code: $filter('uppercase')(employee.name);

Filters using parameter

HTML: <span>{{ employee.feedback | number : 2 }}</span>
Angular Expression: <span ng-bind="employee.feedback | number : 2"></span>
Code: $filter('number')(employee.feedback, 2);

Chained filters

HTML: <span>{{ employee.name | limitTo : 3 | lowercase }}</span>
Angular Expression: <span ng-bind="employee.name | limitTo : 3 | lowercase"></span>
Code: var result = $filter('limitTo')(employee.name, 3);
           $filter('lowercase')(result);

Expression filter composition (within ng-repeat)

You can compose multiple filter expressions by using parenthesis ( object | filter : param ) + ( object | filter : param )

HTML: <span>{{ (employee.name | limitTo : 3 | lowercase) + $index }}</span>
Angular Expression: <span ng-bind="(employee.name | limitTo : 3 | lowercase) + $index"></span>

Demo code: link

AngularJs Meetup South London Collection | this article