JohnDizzle
JohnDizzle

Reputation: 1338

Check result value and add String AngularJS

I am fetching a number (percentage) from a service and want to display it in a proper way with the percentage sign behind the number. In some cases the service returns 'N/A' if the number isn´t aviable so I can´t hardcode the % in my html due to the fact that it would result 'N/A'% in the final page.

So the question which comes up to me is:

How can I check wether my result is a number so I can add a char/string in in a simple way directly in the HTML code or do I have to check the returned value of my service in the controller/JS-code ?

I tried something like this but it doesn't work due to an error message with unexpected chars.

Average User Rating:</b> {{ user.Rating=='N/A' ? 'N/A' : user.Rating '%'}} <br>

Upvotes: 0

Views: 63

Answers (2)

Yerken
Yerken

Reputation: 1942

More reusable solution:

app.filter('percentizer', function(){
        return function(value){
            if (!isNaN(value)) return value + "%";
            else return value;
        }
    });
{{user.Rating | percentizer}}

Upvotes: 1

zucker
zucker

Reputation: 1112

Add + sign:

{{ user.Rating=='N/A' ? 'N/A' : user.Rating + '%'}}

Upvotes: 1

Related Questions