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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With