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

Jimmy
  • 428
  • 5
  • 19
  • maybe because $scope.name was not defined yet ? What about if you init $scope.name to 'name undefined' ? – Walfrat Apr 13 '16 at 13:05

1 Answers1

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.

Scott
  • 860
  • 8
  • 10
  • Thanks for your answer. I guess this is more of a general javascript question. Why does `name && show === undefined` and not `show && name` – Jimmy Apr 15 '16 at 12:41
  • 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. – Scott Apr 16 '16 at 05:28
  • The [MDN docs for logical operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators) are very thorough and a lot better than my explanation as well. – Scott Apr 16 '16 at 05:29