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.


(function () {
   'use strict';

      .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"); 



<!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 />

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



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, Senior Consultant, Microsoft .NET and Web Technologies