Angularjs – Show True/False as Yes/No

All we need is an easy explanation of the problem, so here it is.

Is there a simple way to show a true/false value as yes/no?

I am retrieving from the Database a JSON that contains :

[Object, Object, “WithCertification”: true]

This is the html:

With Certification {{elem.WithCertification}}

Is displaying this:

With Certification true

I want it to display this:

With Certification yes

Is there a way without having to go to the controller to change the true/false to yes/no?

Anyhow I need to change it, any suggestions?

Thank you.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can have ternary operators inside Angular Expressions, so just do this:

With Certification {{elem.WithCertification?'yes':'no'}}

Method 2

{{elem.WithCertification == true ? "Yes" : "No"}}

Method 3

You can use either a filter or a ternary operator. The filter would probably be better from what i’ve read ternary operators are frowned upon.

app.filter('YesNo', function(){
        return function(text){
          return text ? "Yes" : "No";
        }
      })

The code is fairly simple set your app.filter, give it a name, inside pass an anon function, returning a function that takes your true,false as a param, then return the text and determine if true or false, if true return yes, otherwise no.

Alternatively do it inside the tag.

<td>{{item.value ? "Yes":"No"}}</td>

You can see this working here http://plnkr.co/edit/altgrjKhXHACmczOvGFw

Method 4

The best way is to create a custom filter, as it is best to put as less logic in the view as possible. Below is a sample code showing you how to achieve this.

angular.module('myApp', [])
.filter('yesOrNo', function() {
return function(input) {
  return input === 'true' ? 'yes' : 'no' ;
};
})

In html, you would just do:-

With Certification {{elem.WithCertification | yesOrNo}}

Method 5

If this is a one time case, I agree with Joseps answer. Use:

With Certification {{elem.WithCertification?'yes':'no'}}

However, if you intend to use this more often, I would recommend using a filter. A very similar case is explained in the AngularJS tutorial step 9

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply