Monday, January 4, 2016

AngularJS - Custom Filters

AngularJS Filters helps to filter/format data to be displayed to the users. Mostly filers are used in data binding expressions in HTML templates, but you can also use inside controllers, services and directives. AngularJS provides many useful built-in filters, here is a list of some important options:

  • uppercase - used to transform text to upper-case
  • currency - transform a number in currency format
  • number - an expression is formatted as number
  • date - formats a date to string

Following is an example, how we apply filter to an expression:

{{name | uppercase }}

Where name is a model variable in $scope object and uppercase is the name of the filter. A filter is separated from expression by a vertical pipe character (|).

Lets start creating our custom filter. To register a filter we use the function filter() from angular module. First argument is the name of the filter, and second argument is a the factory function used to define the filter's functionality. Filters can accept arguments, so you also use filters in more customized way by adding arguments based on your requirements.

The following snippet creates a filter to replace spaces with some other character (passed in argument).

demoApp.filter('replaceSpaces',function(){
    return function (input, replaceWith) {

        return input.replace(/ /g, replaceWith);
    }
});

And this is how we use this filter in html templates:

{{'Spaces should be removed from this text.' | replaceSpaces : '-'}}

Here we applied filter replaceSpaces with argument '-', separated by ":". So this filter will replace all the occurrences of white spaces with dash sign (-) (or any other character you passed in the argument).

No comments:

Post a Comment