nemo_87
nemo_87

Reputation: 4781

If value is 0 then return empty string in Angularjs

Is it possible to return empty string when some value is "0", but from HTML page using angularJs?

If I have something like this:

<p>External | Year of Birth: {{profileCtrl.person.year}}</p>

Can I write some expression right there that will check the value for profileCtrl.person.year? If the value is "0" then return empty string, else return value of profileCtrl.person.year.

Something like this is very easy to do in languages like C#, but since I am very new to Angular I was unable to find out if this technology has a power to do such thing?

Can someone help me out with this maybe?

Upvotes: 1

Views: 5282

Answers (6)

Nina Scholz
Nina Scholz

Reputation: 386520

You could use a logical OR ||, which uses the second value if the first value is falsy.

<p>External | Year of Birth: {{profileCtrl.person.year || ""}}</p>

Another solution could be to show the wole part, with ng-show attribute and a truthy value. On a falsy value the part is hidden.

<p ng-show="profileCtrl.person.year">External | Year of Birth: {{profileCtrl.person.year}}</p>

Upvotes: 2

pejman
pejman

Reputation: 798

you can use filter in your code for return empty

//js file
app.filter("filterName",function(){
    return function(input){
           switch(input){
           case 0:
           return "";
    }
});

<!-- html page -->
{{input | filterName}}

Upvotes: 0

Akash Nigam
Akash Nigam

Reputation: 417

You can do it like this:

{{profileCtrl.person.year === 0 ? "" : profileCtrl.person.year}}

Upvotes: 2

Lazyexpert
Lazyexpert

Reputation: 3154

Use ternary operator:

<p>External | Year of Birth: {{profileCtrl.person.year !== 0 ? profileCtrl.person.year : ""}}</p>

Another approach might be (haven't checked):

<p>External | Year of Birth: {{profileCtrl.person.year || ""}}</p>

Upvotes: 0

Christos
Christos

Reputation: 53958

You could use the ternary operator ?:

{{ profileCtrl.person.year === 0 ? "" : profileCtrl.person.year }}

Upvotes: 2

Tom Johnson
Tom Johnson

Reputation: 689

You can use a ternary operator to achieve this;

{{profileCtrl.person.year === 0 ? "" : profileCtrl.person.year}}

This basically says, if it's 0 provide "", else provide the year.

Hope it helps!

Upvotes: 2

Related Questions