Tuesday, November 18, 2014

AngularJS Boolean display filter

Sometimes we may have to show a Boolean value to the user. The examples could be user is active or not. In my scenario whether a patient is premature birth or not. We typically store this information in the database or other persistence layer as a Boolean variable. When we show this property to the user, it will be shown as true or false.
Showing true or false to the user is not a very good user experience, instead of true or false we should show yes or no (or something similar) to the user. For transforming the Boolean value to more user friendly text I am using a filter in angular. As you know filter is used for format or transform the expression for the display to the user.
Here is my filter which formats or transforms the Boolean expression to display to the user
'use strict'

angular.module('pos').filter('boolText', boolText);

function boolText() {
    return function (boolValue) {
        if (boolValue === true)
            return "Yes";
        else
            return "No";
    }
}

The above filter can then be used in our bindings as below
{{vm.patientModel.PrematureBirth | boolText }}

As you see a simple reusable Boolean filter provides a user friendly display of all our Boolean variables in the module

1 comment: