AngularJS Your First Filter


Example

Filters are a special type of function that can modify how something is printed out to the page, or can be used to filter an array, or a ng-repeat action. You can create a filter by calling the app.filter() method, passing it a name and a function. See the examples below for details on syntax.


For example, let's create a filter that will change a string to be all uppercase (essentially a wrapper of the .toUpperCase() javascript function):

var app = angular.module("MyApp", []);

// just like making a controller, you must give the
// filter a unique name, in this case "toUppercase"
app.filter('toUppercase', function(){
    // all the filter does is return a function,
    // which acts as the "filtering" function
    return function(rawString){
        // The filter function takes in the value,
        // which we modify in some way, then return
        // back.
        return rawString.toUpperCase();
    };
}); 

Let's take a closer look at what's happening above.

First, we're creating a filter called "toUppercase", which is just like a controller; app.filter(...). Then, that filter's function returns the actual filter function. That function takes a single object, which is the object to be filtered, and should return the filtered version of the object.

Note: In this situation, we're assuming the object being passed into the filter is a string, and therefore know to always use the filter only on strings. That being said, a further improvement to the filter could be made that loops through the object (if it's an array) and then makes every element that is a string uppercase.

Now let's use our new filter in action. Our filter can be used in two ways, either in an angular template or as a javascript function (as an injected Angular reference).

Javascript

Simply inject the angular $filter object to your controller, then use that to retrieve the filter function using its name.

app.controller("MyController", function($scope, $filter){
    this.rawString = "Foo";
    this.capsString = $filter("toUppercase")(this.rawString);
});

HTML

For an angular directive, use the pipe (|) symbol followed by the filter name in the directive after the actual string. For example, let's say we have a controller called MyController that has a string called rawString as a element of it.

<div ng-controller="MyController as ctrl">
    <span>Capital rawString: {{ ctrl.rawString | toUppercase }}</span>
</div>

Editor's Note: Angular has a number of built in filters, including "uppercase", and the "toUppercase" filter is intended only as a demo to easily show off how filters work, but you do not need to built your own uppercase function.