Angular JS Magazine

marți, 16 septembrie 2014

Working with Currency Filter

In this tip you can see how to use the Angular JS built-in curreny filter. It can be used to format a number as currency - it uses two decimal spaces and adds the currency symbol:

<!DOCTYPE html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="../angular/angular.min.js"></script>
    <link href="../bootstrap/css/bootstrap.css" rel="stylesheet" />
    <link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet" />
<div ng-app="" ng-init="atp=[
     { name: 'Nadal, Rafael (ESP)', rank: 1, prizemoney: '66149345' },
     { name: 'Djokovic, Novak (SRB)', rank: 2, prizemoney: '70704129' },
     { name: 'Federer, Roger (SUI)', rank: 3, prizemoney: '84827704' },
     { name: 'Wawrinka, Stan (SUI)', rank: 4, prizemoney: '13155060' },
     { name: 'Ferrer, David (ESP)', rank: 5, prizemoney: '24034072' }]">

    <div id="atpPanel" class="panel">
        <h3 class="panel-header">ATP SINGLES RANKINGS</h3>
        <table class="table">
                <th>Prize Money (USD)</th>
                <th>Prize Money (EUR)</th>
                <th>Prize Money (GBP)</th>
            <tr ng-repeat="item in atp">
                <td>{{item.prizemoney | currency}}</td>
                <td>{{item.prizemoney | currency:"€"}}</td>
                <td>{{item.prizemoney | currency:"£"}}</td>

In order to work with a more powerful currency formatter you can try Accounting.js which is a small JavaScript library that solves the problem of currency symbol placement and periods vs. commas vs. spaces as separators.