Handle model transformations with Filters in angularjs

angularjs expressions can get fairly complex and contain function invocations. Those functions might serve different purposes but model transformations and formatting are common needs. To cater for those common use-cases angularjs expressions support special formatting (transforming) functions called filters:

{{user.signedUp| date:'yyyy-MM-dd'}}

In this example the date filter is used to format user’s sign-up date.

A filter is nothing more than a global, named function that is invoked in view using the pipe (|) symbol with parameters separated by the colon (:) character. In fact we could re-write our sample code like so (provided that the formatDate function is defined on a scope):

{{formatDate(user.signedUp, 'yyyy-MM-dd')}}

Advantages of filters are two-fold: they don’t require registration of functions on a scope (so are readily available for each and every template), and usually offer more convenient syntax as compared to regular function calls.

Recommended :  Generate bar codes directly in your laravel app

The simple example also shows that filters can be parameterized (or in other words, arguments can be passed to a filter function): here we specify a date format as an argument to the date filter.
Several filters can be combined (chained) to form a transformation pipeline. As an example we can format a string by limiting its length to 80 characters and convert all the characters to lowercase:

{{myLongString | limitTo:80 | lowercase}}

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares