How to conditionally format data using custom AngularJS filter


If you are displaying data from the database and you want to format data based on certain condition, you can create custom AngularJS filter to achieve this functionality.

AngularJS

(function () {
   'use strict';

   angular
      .module('app', [])
      .controller('DemoController', DemoController)
      .filter('StatusFormatFilter', StatusFormatFilter);

      function DemoController (){
         var vm = this;
         vm.users = [ 
            {Id: 1, Name: "Joseph", Status: true}, 
            {Id: 2, Name: "Peter", Status: false}, 
            {Id: 3, Name: "Parker", Status: true}, 
            {Id: 4, Name: "Mark", Status: false}, 
         ];
      }

      function StatusFormatFilter (){ 
         return function(input){ 
            return (input == true ? "Approved" : "Not Approved"); 
         }; 
      }

})();

HTML

<!DOCTYPE html>
<html lang="en-US">
    <body ng-app="app">

        <div ng-controller="DemoController as vm">
            <div ng-repeat="user in vm.users">
                Id: <span>{{user.Id}}</span><br />
                Name: <span>{{user.Name}}</span><br />
                Status: <span>{{user.Status | StatusFormatFilter}}</span><br />
                <hr />
            </div>
        </div>

        <script src="angular.min.js"></script>
        <script src="app.js"></script>

    </body>
</html>

Output

Id: 1
Name: Joseph
Status: Approved
_________________________________________________________________________
Id: 2
Name: Peter
Status: Not Approved
_________________________________________________________________________
Id: 3
Name: Parker
Status: Approved
_________________________________________________________________________
Id: 4
Name: Mark
Status: Not Approved

 

Notice how the status true or false is replaced with the custom text Approved or Not Approved in the output.

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments