Angular JS Magazine

vineri, 26 septembrie 2014

Writing a Simple Custom Filter

When built-in filter cannot help you, is time to write a custom filter. Custom filters are the responsability of the Module.filter method. This method have two arguments:

  • the name of the filter that will be created 
  • the factory function that creates the worker function that will do the work
In the next code, you can see how to create a simple filter that replace the rank number of the first three ATP players (1,2 and 3) with a star (\u272A):

<!DOCTYPE html>
<html ng-app="atpModule">
<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"/>
    <script>
        angular.module("atpModule", [])
                .controller("atpCtrl", function ($scope) {
                })
                .filter('starsForStars', function () {
                    return function (item) {
                        if(item <=3 ) {
                            item="\u272A";
                            return item;
                        } else return item;
                    };
                });
    </script>
</head>
<body>
<div ng-controller="atpCtrl" ng-init="atp=[
     { name: 'Nadal, Rafael (ESP)', rank: 1, age: '28', prizemoney: 66149345 },
     { name: 'Djokovic, Novak (SRB)', rank: 2, age: '27', prizemoney: 70704129 },
     { name: 'Federer, Roger (SUI)', rank: 3, age: '33', prizemoney: 84827704 },
     { name: 'Wawrinka, Stan (SUI)', rank: 4, age: '29', prizemoney: 13155060 },
     { name: 'Ferrer, David (ESP)', rank: 5, age: '32',  prizemoney: 24034072 },
     { name: 'Tsonga, Jo-Wilfried (FRA)', rank: 11, age: '29', prizemoney: 1708240 },
     { name: 'Verdasco, Fernando (ESP)', rank: 33, age: '30', prizemoney: 689219 },
     { name: 'Mayer, Leonardo (ARG)', rank: 25, age: '27', prizemoney: 946294 }]">

    <div id="atpPanel" class="panel">
        <h3 class="panel-header">ATP SINGLES RANKINGS</h3>
        <table class="table">
            <thead>
            <tr>
                <th>Rank</th>
                <th>Name</th>
                <th>Age</th>
                <th>Prize Money</th>
            </tr>
            </thead>
            <tbody>
            <tr ng-repeat="item in atp">
                <td>{{item.rank | starsForStars}}</td>
                <td>{{item.name}}</td>
                <td>{{item.age}}</td>
                <td>{{item.prizemoney | currency:"$"}}</td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>