Custom Filter example in AngularJS

Last Reply 7 months ago By dharmendr

Posted 7 months ago

How to use AngularJS Custom Filters

You are viewing reply posted by: dharmendr 7 months ago.
Posted 7 months ago Modified on 7 months ago

Hi rani,

The custom filters is a filter that allow you to create your own custom filters logic with help of your own array expressions.

The custom currency filter : {{ Salary | currency:"$"}}

The custom date filter :- {{Date | date:"yyyy-MM-dd HH:mm:ss Z"}}

The custom number filter :- {{ NumberExpressions | number : Fraction_Size}}

Example

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.controller("MyController", function ($scope) {
            $scope.Students = [
                   { Id: 1, Name: "Ram", Salary: 15000 },
                   { Id: 2, Name: "Rahim", Salary: 26500 },
                   { Id: 3, Name: "Ajay", Salary: 16986 },
                   { Id: 4, Name: "Bijay", Salary: 22000 }];
        });
        app.filter('CustomCurrencyFractional', ['$filter', '$locale', function (filter, locale) {
            var currency_Filters = filter('currency');
            var decimalFormat = locale.NUMBER_FORMATS;
            return function (amountVal, currencyType) {
                var currencyValue = currency_Filters(amountVal, currencyType);
                var result = currencyValue.indexOf(decimalFormat.DECIMAL_SEP);
                if (amountVal >= 0) {
                    return currencyValue.substring(0, result);
                } else {
                    return currencyValue.substring(0, result);
                }
            };
        } ]);
    </script>
</head>
<body>
    <div ng-app="MyApp" ng-controller="MyController">
        <table border="1">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Salary</th>
                <th>Salary Fraction</th>
            </tr>
            <tr ng-repeat="student in Students">
                <td>{{student.Id}}</td>
                <td>{{student.Name}}</td>
                <td>{{student.Salary | currency }}</td>
                <td>{{student.Salary | CustomCurrencyFractional:"£" }}</td>
            </tr>
        </table>
    </div>
</body>
</html>

Demo