In Angular, filters give us a nice way to format the data we use in our apps, or present to the user. Angular provides a subset of filters out of the box, or we can write our own. In this post we’ll do just that.

Creation

To create a filter, we simply attach it to our module, name it, and return the data input.

Note: It is best practice to create a module for your filters, aside from your main module.

angular.module('myApp')
  .filter('slug', function () {
    return function (input) {
      if (input) {
        return input;
      }
    };
  });

Ok, so the above filter is getting our data argument, and returning it, but not doing anything. Let’s give it some actual filtering to do. We’ll setup our filter to normalize the data passed to it, by forcing it to lowercase, and replacing any spaces with underscores.

angular.module('myApp')
  .filter('slug', function () {
    return function (input) {
      if (input) {
        return input.toLowerCase().replace(/[^a-z_]/g, '_');
      }
    };
  });

Invoking

Now that we’ve got this sweet filter, let’s use it. Angular gives us the option of invoking filters in either HTML or JS. We’ll go over both.

First, HTML. We call our filter inside an expression using the pipe character inside the {{ }} syntax. This allows us to pipe our date into our expression as an argument.

{{ 'Rob Stinogle' | slug }}

// Displays: rob_stinogle

Second, Javascript. We can invoke our filter by injecting the $filter dependency into our controller. We then have access to both Angular’s and our filters, including our custom slug filter. We can pass both our filter name and data as arguments.

angular.module('myApp')
  .controller('myCtrl', function ($scope, $filter) {
    var userName = 'Rob Stinogle';
    $scope.userSlug = $filter('slug')(userName);
    console.log($scope.userSlug);
  });

// Displays: rob_stinogle

And that’s it! As usual, Angular makes things crazy simple and organized. Let me know if you have any questions!