Angular filters. Create your own filters

Home » Tutorials » JavaScript » Angular filters. Create your own filters
In this tutorial we’ll discuss filters in angular. Angular has got several build-in filters. Also we will create our custom filter with filter method.
There are the list of build-in filters below:

  • uppercase formats string to uppercase.
  • lowercase formats string to lowercase.
  • number formats a number to string.
  • limitTo limit input of data based of specified number.
  • date formats date to specified format.
  • currency formats a number to currency.
  • filter chooses elements from the specified array.
Code lesson (build-in filters)
<!DOCTYPE html>
<html ng-app="filtersApp">
    <head>
        <meta charset="utf-8">
        <title></title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body ng-controller="filterCtrl">

        <p>{{upperWord | uppercase}}</p>
        <p>{{lowerWord | lowercase}}</p>
        <p>{{456.78 | number:1}}</p>
        <p>{{50 | currency}}</p>
        <p>{{12834554645 | date: 'dd.mm.yyyy'}}</p>


        <script src="angular.js"></script>
        <script>
            var app = angular.module("filtersApp", []);

            app.controller('filterCtrl', function($scope){
                $scope.upperWord = "Камиль";
                $scope.lowerWord = "Камиль";
            });

        </script>

    </body>
</html>
As you understood from last lessons, filters were written after straight line.
Through a two-way data binding in angular we can use filters with different events – for example, filter by click or filter by user input. In examples it is sortByName filter and filter with selectPlayers model (live search) accordingly.

But like any framework, angular concepts are developers can expand opportunities of build in functionality. In our case it is creation of custom filters. For this purpose angular has got filter method. It has got two parameters – filter name and function, which will filter data.

Code lesson
<!DOCTYPE html>
<html ng-app="playersApp">
    <head>
        <meta charset="utf-8">
        <title></title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <style>
            /*input.ng-invalid-required {
                border: 1px solid red;
            }*/
        </style>
    </head>
    <body>

        <div class="container" ng-controller="playerCtrl">
            <div class="row">
                <div class="col-md-12">
                    <form class="form-horizontal" name="addPlayerForm" novalidate>
                        <legend>Список футболистов</legend>
                          <div class="form-group" ng-class="{'has-error': addPlayerForm.pName.$error.required && addPlayerForm.pName.$dirty}">
                            <label for="playerName" class="col-sm-4 control-label">Имя игрока</label>
                            <div class="col-sm-8">
                              <input type="text" required name="pName" ng-model="playerName" class="form-control" id="playerName" placeholder="Имя игрока">
                              <span class="error" ng-show="addPlayerForm.pName.$dirty && addPlayerForm.pName.$error.required">Введите имя игрока!</span>
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="playerTeam" class="col-sm-4 control-label">В какой команде играет</label>
                            <div class="col-sm-8">
                              <input type="text" name="pTeam" ng-model="playerTeam" class="form-control" id="playerTeam" placeholder="В какой команде играет">
                            </div>
                          </div>
                          <div class="form-group" ng-class="{'has-error': addPlayerForm.pCountry.$error.required && addPlayerForm.pCountry.$dirty}">
                            <label for="playerCountry" class="col-sm-4 control-label">Гражданство</label>
                            <div class="col-sm-8">
                                <input type="text" required name="pCountry" ng-model="playerCountry" class="form-control" id="playerCountry" placeholder="Гражданство">
                                <span class="error" ng-show="addPlayerForm.pCountry.$dirty && addPlayerForm.pCountry.$error.required">Игрок не может быть без гражданства!</span>
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="playerGoals" class="col-sm-4 control-label">Сколько голов забил</label>
                            <div class="col-sm-8">
                              <input type="text" name="pGoals" ng-model="playerGoals" class="form-control" id="playerGoals" placeholder="Сколько голов забил">
                            </div>
                          </div>
                          <div class="form-group">
                              <div class="col-sm-8 col-sm-offset-4">
                                  <button ng-disabled="addPlayerForm.pName.$invalid || addPlayerForm.pCountry.$invalid" ng-click="addPlayer(playerName, playerTeam, playerCountry, playerGoals)" class="btn btn-default">Добавить</button>
                              </div>
                          </div>
                    </form>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <input type="text" name="pSelect" ng-model="selectPlayers" class="form-control">
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th ng-click="sortByName('name')">Игрок</th>
                                <th>Команда</th>
                                <th>Национальность</th>
                                <th>Сколько голов забил</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!--<tr ng-repeat="player in players | orderBy:nameSorting | filter: selectPlayers | limitTo:2">
                                <td>{{player.name}}</td>
                                <td>{{player.team}}</td>
                                <td>{{player.country}}</td>
                                <td>{{player.goals}}</td>
                            </tr>-->
                            <tr ng-repeat="player in players | goalsFilter">
                                <td>{{player.name}}</td>
                                <td>{{player.team}}</td>
                                <td>{{player.country}}</td>
                                <td>{{player.goals}}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <script src="angular.js"></script>
        <script>
            var app = angular.module("playersApp", []);

            var model = [];


            app.controller("playerCtrl", function($scope){
                $scope.players = model;
                $scope.orderByFunction = function(player){
                    return parseInt(player.goals);
                };
                $scope.addPlayer = function(playerName, playerTeam, playerCountry, playerGoals) {
                    $scope.players.push({name: playerName, team: playerTeam, country: playerCountry, goals: playerGoals});
                }

                $scope.sortByName = function(p) {
                    $scope.nameSorting = p;
                }

            });

            app.filter("goalsFilter", function() {
                return function(item) {
                    var tenGoals = [];
                    for(i=0; i<item.length; i++) {
                        if(item[i].goals > 10) {
                            tenGoals.push(item[i]);
                        }
                    }
                    return tenGoals;
                }
            });
        </script>

    </body>
</html>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Подписаться на рассылку

Будьте в курсе - получайте последние статьи на свой email

Ваша подписка успешно оформлена

Pin It on Pinterest

Share This