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>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="../angular/angular.min.js"></script>
    <link href="../bootstrap/css/bootstrap.css" rel="stylesheet" />
    <link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet" />
</head>
<body>
<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">
            <thead>
            <tr>
                <th>Name</th>
                <th>Rank</th>
                <th>Prize Money (USD)</th>
                <th>Prize Money (EUR)</th>
                <th>Prize Money (GBP)</th>
            </tr>
            </thead>
            <tbody>
            <tr ng-repeat="item in atp">
                <td>{{item.name}}</td>
                <td>{{item.rank}}</td>
                <td>{{item.prizemoney | currency}}</td>
                <td>{{item.prizemoney | currency:"€"}}</td>
                <td>{{item.prizemoney | currency:"£"}}</td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>

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.