AngularJS filters are simple javascript functions registered via a filter factory function.

The factory returns a function taking as first parameter the filter input and any other parameter possibly passed is used as further filter argument. 

The following example shows a filter encrypting a string into its corresponding rot13 value

    .filter("rot13", function() {
        return function(input) {
                return input.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
                // if no string
                return "";

The filter obtained can be used within a template  


its output is "sbb".

Such filters are "chainable", so you can also write 


its output is "foo".

You can also use it within your code 

$scope.unsecurePassword = $filter("rot13")("foo");

The corresponding function should be "stateless and idempotent". This means that, given a certain input, the function will always output the same result.  AngularJS works based upon such properties and executes the filter function only when the input changes.

For example, a function which can not be implemented is a filter shuffling the contents of an array, as this would imply a loop at $digest.

Antonello Pasella

Freelance Frontent Developer, PHP Expert , Website , Git home page , @apasella , Linkedin profile
15+ year experience in web programming, fucused on cross platform frontend and game development (even remote). Web enthusiast and game passionate, full stack programmer ready to dive into new projects. Top skills: AngularJS Phonegap PHP

All articles by Antonello Pasella


comments powered by Disqus


Follow Us