javascriptangularjsboolean-operationsone-time-binding

AngularJs one time binding and order of values with boolean operators


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


Solution

  • 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.