AngularJS already comes with built-in filters, but even then, we'll certainly need to create our own filters in order to fulfill specific requirements.
To create a new filter, you just need to register it to the application's module, returning the filter function. This function takes the inputted value as the first parameter and other additional arguments if necessary.
Angular has a
.filter()
method for each Module, which means we can write our own custom filters.
app.filter('<filterName>', function () {
return function () {
return;
};
});
The returned function gets invoked each time Angular calls the filter, which means two-way binding for our filters. The user makes a change, the filter runs again and updates as necessary. The name of our filter is how we can reference it inside Angular bindings.
Custom filter to create a Upper case character.
app.filter('toUpper', function () {
return function (item) {
return item.toUpperCase();
};
});
Filter method, creating `toUpper` a globally available filter in our 'app' module
app.filter('toUpper', function () {
// function that's invoked each time Angular runs $digest()
// pass in 'item' which is the single Object we'll manipulate
return function (item) {
// return the current 'item', but call `toUpperCase()` on it
return item.toUpperCase();
};
});
snippet
var app = angular.module('app', []);
app.filter('toUpper', function () {
return function (item) {
return item.toUpperCase();
};
});
app.controller('employeeCtrl', function () {
this.Name = 'John Abraham';
});
Then we declare it in the HTML:
<div ng-app="app">
<div ng-controller="employeeCtrl as employee">
<p>
{{ employee.Name | toUpper }}
</p>
</div>
</div>