5

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.

5
  • 1
    Please provide the code from your controller as well as the template. Are you using this on the controller? If so, then the controller is being used as a viewmodel so you would access the data somewhat differently than if you were using scope.
    – Dom
    Jan 27, 2015 at 19:15
  • 3
    I can't reproduce: plnkr.co/edit/Oa9JsDwW1TVjwxIYzov9?p=preview. The problem is elsewhere.
    – JB Nizet
    Jan 27, 2015 at 19:21
  • I can't reproduce your issue either: jsfiddle - can you extend this fiddle/create a new one that reproduces the issue?
    – JRulle
    Jan 27, 2015 at 19:26
  • There's no really a problem, kinda, I'm just confused on how it works, I will add a plunkr, one minute.
    – Dvid Silva
    Jan 27, 2015 at 19:39
  • Random I wasn't able to reproduce either. plnkr.co/edit/FvwEmAcnqGyX6iLsJUcQ?p=preview I will try and look for other things that could be getting on the way.
    – Dvid Silva
    Jan 27, 2015 at 19:49

1 Answer 1

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.