Part 8 : Filters in Angular Js

Filters are used to change modify the data and can be clubbed in expression or directives using pipe (|) character. 

A list of some common filters and their usage:


Filter Name Description
Uppercase converts a text to upper case text.
Lowercase converts a text to lower case text.
Currency formats text in currency format.
Filter filter the array to a subset of it based on certain conditions.
Orderby Orders the array based on certain conditions.
Date Format a date to a specified format.
Json Format an object to a Json String.
Number Format number to a string.
LimitTo Limits an array or string into a specified number of elements or characters.

 Example of Uppercase and Lowercase filter.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <title></title>
       <meta charset="utf-8" />
</head>
<body>
    <div ng-controller="MyCtrl">
        My Name is {{firstName|uppercase}} {{lastName|lowercase}}
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("MyCtrl", function ($scope) {
            $scope.firstName = "Rohit",
            $scope.lastName = "Singh"
        });
    </script>
</body>
</html>

Output:

My Name is ROHIT singh.

Example of Currency filter.

<input type="text" ng-model="salary" />
Salary entered by you is: {{salary | currency }}

Output:

Salary entered by you is: $145.00.

 Example of Custom Filter filter.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <title></title>
       <meta charset="utf-8" />
</head>
<body>
    <div ng-controller="MyCtrl">
       <ul>
           <li ng-repeat="name in names | filter:'y'">
               {{name}}
           </li>
       </ul>
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("MyCtrl", function ($scope) {
            $scope.names = [
                'Ankush',
                'Vinay',
                'Saurav',
                'Sandeep',
                'Gaurav',
                'Sanjay',
                'Akshay',
            ];
        });
    </script>
</body>
</html>

Output:
  • Vinay
  • Sanjay
  • Akshay
Explanation about above example: The above example only shows the names of those students who have letter 'Y' in their name.


No comments:

Post a Comment