Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use filters in AngularJS?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 689
    Comment on it

    A filter is used to format data to be displayed to the user. These can be used in controllers,templates or services and we can also easily define our own filters. Some of the built-in filters in AngularJS are :-
    1.uppercase - formats or converts text to uppercase text.
    2.lowercase - formats or converts text to lowercase text.
    3.filter - selects or filters a subset from an array based on certain criteria.
    4.order by - sets an order based on certain criteria.
    5.currency - formats text into currency format.
    6.date - It formats a date to a specified format.
    Some examples of its usage is as follows :-
    1.

    <div ng-app="myExample ng-controller=Egctrl>
    
    <p>The day is {{ Day | uppercase }}</p>
    
    </div>
    
    <script>
    angular.module('myExample', []).controller('Egctrl', function($scope) {
          $scope.Day = Sunday
    });
    </script>


    2.

    <div ng-app="myExample" ng-controller="Egctrl">
    
    <h1>Cost is: {{ cost | currency }}</h1>
    
    </div>
    
    <script>
    var app = angular.module('myExample', []);
    app.controller('Egctrl', function($scope) {
        $scope.cost = 50;
    });
    </script>

    Custom Filter- We can create our own filter very easily by jaunt appending .filter(‘filterName', function(){}) with our controller. This means that the filter is registered as a factory function with our module. Once it is created it behaves on a global scope. For example:-

    var myExample = angular.module(MyExample', []);
    
    //Create a Filter
    myExample.filter("textrev, function() {
    
            //Defining the filter function
             return function(data) {
     
                     var Finalresult = "";
                     data = data || "";
    
                    for (var i=0; i<data.length; i++) {
                           Finalresult = data.charAt(i) + Finalresult;
                     }
        
                    return Finalresult;
             };
    });

    Now using this filter in your HTML:
     

    <body ng-app="MyExample">
           <input type="text" ng-model="text" placeholder="Enter something/>
            <p> Reversed Text: {{ text | textrev }}</p>
    </body>

     

 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: