Displaying and Formatting Data
Costly data transformations in filters
Filters, when used in a template, become integral part of the AngularJS expression,
and as such are frequently evaluated. In fact, such filter functions are called multiple
times on each digest cycle. We can easily see this in practice by creating a logging
wrapper around the uppercase filter:
angular.module('filtersPerf', [])
.filter('logUppercase', function(uppercaseFilter){
return function(input) {
console.log('Calling uppercase on: '+input);
return uppercaseFilter(input);
};
});
Upon using this newly defined filter in a markup like:
<input ng-model="name"> {{name | logUppercase}}
We will see that the log statement is written at least once (usually twice) for each
keystroke! This experiment alone should convince you that filters are executed often
so it is highly preferable that they execute fast.
Don't be surprised to see that a filter is called multiple times in a row;
this is AngularJS dirty checking at work. Strive to write your filters so
they do light, fast processing.
Unstable filters
Since filters are called multiple times it is reasonable to expect that a filter responds
with the same return value if the input doesn't change. Such functions are called
stable with respect to their parameters.
Things can get easily out of hand if a filter doesn't have this property. To see the
disastrous effects of unstable filters let's write a malicious random filter that selects
a random element from an input array (it is unstable):
angular.module('filtersStability', [])
.filter('random', function () {
return function (inputArray) {
var idx = Math.floor(Math.random() * inputArray.length);
return inputArray[idx];
};
})