Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create a custom filter in AngularJS?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 153
    Comment on it

    In AngularJS, Filters are used to format data which is served to the user. Filters are added to expressions by using the pipe(|) character and followed by a filter method. There are a lot of in-built filters available in AngularJS


     For example:
      currency: This filter is used to convert a number to a currency format.
      uppercase: This filter is used to convert a string to upper case.

     

    We can also create a custom filer according to our requirement in app.

    In the following example, we created a 'customStringFormat' custom filter which is convert the country name to lower in case using javaScript function.


    Here,
    The AngularJS app is defined using ng-app directive i.e. ng-app="angularApp" and this app runs inside the <ul>.


    Defined countryCtrl named controller using directive ng-controller i.e. ng-controller="countryCtrl"  which is a JavaScript function  and AngularJS called the countryCtrl controller with a $scope object .

     

    Registered a custom filter named 'customStringFormat' using factory filter method and passed country element to perform custom operation.

     

    <!DOCTYPE html>
    <html>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>
    <ul ng-app="angularApp" ng-controller="countryCtrl">
    <li ng-repeat="n in countryArr">
        {{n | customStringFormat}}
    </li>
    </ul>
    
    <script>
    var app = angular.module('angularApp', []);
    app.filter('customStringFormat', function() {
        return function(t) {
            return toLowerCase();
        };
    });
    app.controller('countryCtrl', function($scope) {
        $scope.countryArr = ['INDIA', 'ENGLAND', 'AUSTRAILIA', 'CHINA', 'NORWAY'];
    });
    </script>
    
    <p>Create custom filter in angularjs</p>
    </body>
    </html>

     

    The output will be:

    • india
    • england
    • austrailia
    • china
    • norway

    Creating a custom filter in angularJS

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: