AngularJS Filters

AngularJS can manipulate how values are displayed by using a feature called filters. This article explains how to use filters.

What Is a Filter?

AngularJS can display various values by using tags written as {{}}. If all you do is display values, it is hardly programming. However, displaying a value does not always mean “show the passed value exactly as it is.”

For example, suppose you want to show the symbol when displaying numeric values as amounts. In that case, adding the symbol to every output location is not necessarily easy.

This is when “filters” are used. A filter is a feature that can automatically manipulate various values. It is used as follows.

{{variable | filter}}

Add the | symbol after the variable, then provide the filter. To use several filters at the same time, write them like this.

{{variable | filter1 | filter2 | ...}}

You can connect as many as needed.

AngularJS itself provides several common filters that can be used at any time. You can also program and use your own filters.

Creating a Module and Controller

Let us create an example that uses filters. First, write the program.

The following is a simple example program. Save it as script.js.

var myapp = angular.module('myapp',[]);
var helo = myapp.controller('HeloController',
    function(){
        this.count = 0;
        this.data = [
            {id:0,name:'no data',price:0,get:false,date:1450100000000},
            {id:1,name:'Android phone',price:7800,get:true,date:1450400000000},
            {id:2,name:'New iPhone',price:549020,get:false,date:1450200000000},
            {id:3,name:'windows phone',price:38765,get:true,date:1450300000000}
        ];
        this.getData = function(){
            return this.data[this.count].id + ': ' + 
                this.data[this.count].name + ', ' + 
                this.data[this.count].price + '.' +
                this.data[this.count].date;
        };
    }
);

This time, the HeloController class defines the properties and method count, data, and getData. data represents something like a very simple catalog. It has information such as ID, name, price, a Boolean value indicating whether it has been obtained, and a registration date. The registration date is specified as an integer timestamp value.

We will use filters when displaying this data in a template.

Filtering Values

Let us display data by using filters. The HTML example is as follows.

<! DOCTYPE html>
<html>
<head>
    <title>AngularJS Sample</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="script.js"></script>
    <style>
    body { color:gray; }
    h1 { font-size:18pt; font-weight:bold; }
    span.label { display:inline-block;width:50px; color:red; }
    input { width:100px; }
    .msg { font-size:14pt; font-weight:bold;color:gray; }
    th { color:#eee; background-color:#999; padding: 5px 10px;}
    td { color:#333; background-color:#ddd; padding: 5px 10px;}
    </style>
</head>
<body ng-app="myapp" ng-init="num=0">
    <h1>Data Display</h1>
    <div ng-controller="HeloController as ctl">
     
    <table>
    <tr><th>ID</th><th>NAME</th><th>PRICE</th><th>GET?</th><th>DATE</th></tr>
    <tr ng-repeat="obj in ctl.data">
        <td>{{obj.id}}</td>
        <td>{{obj.name}}</td>
        <td>{{obj.price | currency:'₩'}}</td>
        <td>{{obj.get}}</td>
        <td>{{obj.date | date:'yyyy-MM-dd'}}</td>
    </tr>
    </table>
     
    </div>
</body>
</html>

Display the source code in the browser again.

This time, filters are set for the PRICE and DATE items. Let us look at the parts that output each value.

PRICE Output

{{obj.price | currency : '₩'}}

After obj.price, a filter named currency is set. This filter formats a number as money. Some filters require values to be prepared depending on the filter. currency is one of them, and by specifying , you can set Korean won notation. In the output display, you should be able to confirm that it appears in a format such as ₩ 7,800.00.

DATE Output

{{obj.date | date : 'yyyy-MM-dd'}}

After obj.date, a filter named date is set. This filter formats a Date object value into a specific format. Here it is set to yyyy-MM-dd. This displays dates in a format such as 2015-12-14.

The date value was an integer timestamp. If you use the date filter, it creates a Date object based on the timestamp and obtains text formatted according to the specified format.

In this way, filters can make simple numbers appear as money or dates.

Standard Filters

Filters are very easy to use, but you cannot use them if you do not know which filters are available. This section explains filters provided by default in AngularJS.

currency

A filter for displaying numbers as money. If you specify only currency, it is displayed in dollars. If you write currency : '₩', it is displayed in Korean won.

date

A filter that formats a Date value as date text in a specified format. You specify a format name or a pattern as its value. The format names and metacharacters that can be used in patterns are as follows.

Format Names

Format name Description
short, shortTime, shortDate Short-format output.
medium, mediumTime, mediumDate Commonly used format output.
longDate, fullDate Long date-format output.

Pattern Metacharacters

Character Description
y Year.
M Month.
d Day.
E Day of week.
H Hour in 24-hour format.
h Hour in 12-hour format.
m Minute.
s Second.
.sss Millisecond.
a AM or PM.
z Time zone.

number

A filter that rounds and displays a number to a specific number of digits. For example, number : 4 displays only the first four digits and rounds the fifth digit.

json

A filter that converts an object’s value to JSON format and outputs it.

uppercase / lowercase

Filters that convert all text to uppercase or lowercase.

Custom Filters

Filters are not limited to the ones provided by default; you can also create your own. A custom filter is defined in the following form.

controller.filter(name, function);

Use the controller’s filter method to register the filter. The arguments require the filter name and a function that implements the filter processing.

The function set as an argument should generally be defined in the following form.

function(val) {
    ... omitted ...
    return value;
}

The argument receives the original value passed through the filter. The returned value is the filtered value. In other words, if you think about how to convert the argument value and return it in the function, you can create filters relatively easily.

getIt Filter

Let us create a simple example. The data prepared in the controller had a get value that indicates purchase status as a Boolean value. Let us create a filter that displays this more clearly.

The example is as follows.

helo.filter('getIt', 
    function(){
        return function(val) {
            return val ? "✔" : "-";
        };
    }
);

Add this to the end of script.js. Then modify the part of the HTML file that displays get, {{obj.get}}, as follows.

<td>{{obj.get | getIt}}</td>

If you apply the filter to get this way, you can confirm that is displayed. Here, depending on the value of val, either or - is returned. If true, is displayed; if false, - is displayed.

Setting Values on Filters

As with currency or date, filters can also be called with some value set. This section explains how to do that.

It is simple. When defining the filter function, specify a second argument to pass a value.

Let us modify the getIt filter created earlier so that it can receive a value. A simple example is shown below.

helo.filter('getIt', 
    function(){
        return function(val,opt) {
            var t = (opt == null) ? '✔' : opt;
            return val ? t : '-';
        };
    }
);

It checks whether the second argument opt is null, and if it is not null, the filter returns that value when true. If it is null, it returns .

Then modify the part of the HTML file that outputs obj.get as follows.

<td>{{obj.get | getIt:'●'}}</td>

Now true is displayed as , and false as -. The value prepared with getIt : '●' becomes the display for true. Try changing it to another value and check whether it displays correctly.


Filters are surprisingly easy to create once you understand how to generate the return value from the argument. Using the filters you create is also very simple. If you can create your own filters according to the purpose, your expressive power becomes much better.