3

What impact does the order in which boolean operators are declared have?

Controller:

$scope.show = false;

$scope.clickMe = function() {
  $scope.show = true;
  $scope.name = 'Name defined'
};

Template:

<button ng-click="clickMe($event)">Click Me</button>
<p ng-if="::(show && name)">show && name</p>
<p ng-if="::(name && show)">name && show</p>

Results in the second p element with the order of name && show displaying after clicking button. I understood that neither p element should display as $scope.show is already defined and one time binding has been used?

plunkr here:

http://plnkr.co/edit/P0E1RhNK9EPh2Pi04c9T?p=preview

1
  • maybe because $scope.name was not defined yet ? What about if you init $scope.name to 'name undefined' ? Commented Apr 13, 2016 at 13:05

1 Answer 1

4

In Angular, one time binding will constantly evaluate the expression until it has a non-undefined value. So in your example, because name is not defined yet name && show constantly evaluates as undefined on every digest until you finally set it. If you use !! to coerce name to a boolean then you'll get different behaviour. From the Angular docs on expressions:

One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value (see value stabilization algorithm below).

So it doesn't evaluate once per se, it evaluates to a value once.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. I guess this is more of a general javascript question. Why does name && show === undefined and not show && name
The && operator doesn't evaluate to a boolean, if the left hand side is falsey then it returns that, otherwise it will return the right hand side. So undefined && false is undefined while false && undefined is false. If name in your example was '' instead, then both ::(name && show) and ::(show && name) would have the same behaviour.
The MDN docs for logical operators are very thorough and a lot better than my explanation as well.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.