Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double pipe (||) in AngularJS Expressions

Tags:

angularjs

On my controller I have something like: this.user = { first_name: "David", full_name: "David Silva" }

The data I get sometimes doesn't have full_name, so I tried this expression: {{user.full_name || user.first_name}}

It seems to be working but after closer inspection I realize that it doesn't behave how it would in regular JS. I was expecting that if full_name was undefined or empty it would try the other one, but instead if the expression after the || is valid it will evaluate to that regardless of the expression on the left.

I couldn't find out why, and I would like to know more about the way this is interpreted to take proper advantage of it.

like image 484
Dvid Silva Avatar asked Sep 28 '22 22:09

Dvid Silva


1 Answers

I've had trouble with the || in angularJS. In order to get the same effect, I've found it best to use the ternary operator. So you write it like this:

user.full_name ?  user.full_name : user.first_name

This is equivalent to

if(user.full_name)
    return user.full_name
else
    return user.first_name

The ternary operator is a little more verbose, but I have found that it works, whereas || has issues.

like image 157
user3413723 Avatar answered Oct 06 '22 19:10

user3413723