AngularJS Custom Filter

Custom Filter

Custom Filter is filter, return something from input by ourselves.
Angular has prepared filters.
But, sometimes we need our own filter for some purposes.

Example

This example is based on nodejs

customfilter.ejs

<!DOCTYPE html>
<html ng-app="listApp">
<head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <link rel='stylesheet' href='/bower/bootstrap/dist/css/bootstrap.css' />
    <script src="/bower/angular/angular.min.js"></script>
    <script src="/javascripts/filter/controller.js"></script>
    <script src="/javascripts/filter/customfilter.js"></script>
</head>
<body ng-controller="listController">
<div class="container-fluid">
    <div ng-repeat="person in people">
        <div>{{person.name}}</div>
        <div>{{person.nickname}}</div>
        <div>{{person.test | checkmark }}</div>
    </div>
</div>
</body>
</html>

public/javascripts/filter/controller.js

var controller = angular.module('listApp', ['checkmarkFilter']);

controller.controller('listController',['$scope', '$http',
    function ($scope, $http) {
        $http.get('list.json').success(function(data) {
            $scope.people = data;
        });
    }
]);

public/javascripts/filter/customfilter.js

// always return special character
angular.module('checkmarkFilter', []).filter('checkmark', function(){
    return function(input) {
        return input ? '\u2713' : '\u2718';
    }
});

app.js(nodejs)

app.get('/customfilter', function(req, res, next) {
    res.render('customfilter', { title: 'Custom Filter' });
});

// To read json file as it is
app.get('/:file.json', function(req, res, next) {
    var file = approot + '/data/' + req.params.file + '.json';

    fs.readFile(file, 'utf8', function (err, data) {
        if (err) {
            next(err);
        }//console.log(data);
        res.json(JSON.parse(data));
    });
});

Finally, this is sample json file

[
  {
    "name" : "Kotori",
    "nickname" : "Kotori",
    "age" : 17,
    "test" : true
  },
  {
    "name" : "Hanayo",
    "nickname" : "Kayo",
    "age" : 16,
    "test" : false
  },
  {
    "name" : "Eri",
    "nickname" : "Eri",
    "age" : 18,
    "test" : false
  }
]