简体   繁体   中英

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

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.

您可以在Angular Expressions中包含三元运算符 ,所以只需执行以下操作:

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

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

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

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}}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM