Blogs

AngularJS Filter

In this post we’ll analyze the filter functionality provided us by AngularJS.

Filter is a way to format the data displayed. There are several built-in filter but we can create our own filters.

To invoke filters, in the HTML code, we have to use the pipe (|) inside the double braces ( {{ }} )

For example, in this way we’ll capitalize all characters of string:

// result: TODAY IS A BEAUTIFUL DAY
{{ 'Today is a beautiful day' | uppercase }}

A filter can take an argument. You can pass it from the HTML code in this way:

//result: 12.34
{{ 12.3456789 | number:2 }}

Obviously we can use multiple filters in the same time, to do this we have to separate each filter with a pipe.

To use filters in the javascript code, instead, we have to use $filter service:

app.controller('MyController', ['$scope', '$filter',
function($scope, $filter) {
// result: 'STRING TO TRANSFORM'
$scope.myString = $filter('uppercase')('string to transform');
}]);

As mentioned AngularJS provides us several built-in filters, here’s some:

  • date (formats a date passing several format styles)

    //result: April 30, 2014 04:00:00 PM
    {{ mydate | date:'medium' }}
    //result: 04/30/14
    {{ mydate | date:'shortDate' }}
    //result: 04:00 PM
    {{ mytime | date:'shortTime' }}
    //result: Apr 30, 2014
    {{ mytime | date:'MMM d, y' }}
  • currency (formats a value like a currency, default use the local culture settings, otherwise we can pass the currency)
    //result: € 123.00
    {{123 | currency: '€' }}
  • limitTo (create an array or string that contains the specified number of element specified)
    //result: “this”
    {{ ‘this is a sentence | limitTo: 4 }}
  • lowercase (lowercases the string)
  • uppercase (uppercases the string)
  • orderBy (orders the array)
  • CREATE A CUTOM FILTER

    To create a custom filter we have to create it in a module:

    angular.module('myApp.filters', []) .filter('myfilter', function() {
    return function(input) {
    if(input)
    return input[0]
    }
    });

    In this example we uppercase the string and then use our filter that returns its first character.

    //result: T
    {{ ‘this is a sentence’ | uppercase | myfilter }}

    0


Add a Comment