Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - Show True/False as Yes/No

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.

like image 365
SrAxi Avatar asked Oct 02 '14 14:10

SrAxi


4 Answers

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

With Certification {{elem.WithCertification?'yes':'no'}}
like image 180
Josep Avatar answered Nov 14 '22 13:11

Josep


{{elem.WithCertification == true ? "Yes" : "No"}}
like image 42
Yordi Lorenzo Boeit Niet Avatar answered Nov 14 '22 12:11

Yordi Lorenzo Boeit Niet


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

like image 8
Evan Burbidge Avatar answered Nov 14 '22 12:11

Evan Burbidge


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}}
like image 4
Abhishek Jain Avatar answered Nov 14 '22 11:11

Abhishek Jain