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

angular.module("myApp")
    .filter("rot13", function() {
        return function(input) {
            if(angular.isString(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);});
            }else{
                // if no string
                return "";
            }
        };
    })

The filter obtained can be used within a template  

"foo"

its output is "sbb".

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

"foo"

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

comments powered by Disqus

cloudparty

Follow Us