Will the ternary operator be executed on every digest?

Viewed 1011

If I use the ternary operator in my Angular.js view will it be executed on every digest(like functions) or only if the variables necessary for the decision are changed?

Example:

<div>{{ui.isTrue ? "foo" : "bar"}}</div>

or:

<div ng-bind="ui.isTrue ? 'foo' : 'bar'"></div>

Would it be executed on every digest or only when is ui.IsTrue changed?

3 Answers

In AngularJS, every expression including the ternary operator will be executed:

  • First when the page is loaded.
  • And whenever the ui.isTrue variable is changed in the angular app scope.

If you take a look at angular scope documentation and specifically Scope as Data-Model section, you will see that:

Scope is the glue between application controller and the view. During the template linking phase the directives set up $watch expressions on the scope.

The $watch allows the directives to be notified of property changes, which allows the directive to render the updated value to the DOM.

So the view will be always notified when a property in the scope changes, so the ternary expression will be automatically evaluated.

Here is example what you are looking, and yes it will be executed on every digest

var app = angular.module('myApp', []);
app.controller('MyController', ['$scope', MyController]);
function MyController($scope) {
 $scope.isTrue = true;
    setInterval(function() {
      $scope.isTrue = !$scope.isTrue;
      $scope.$digest();
  }, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


<div ng-app="myApp" ng-controller='MyController'>
    <div>{{isTrue ? "foo" : "bar"}}</div>
</div>

Read about Digest

I made a fiddle to test this myself.

http://jsfiddle.net/xuvzzay8/4/

HTML:

<div ng-controller="MyCtrl">    
    {{bool ? ternaryTrue() : ternaryFalse() }}<br/>

    {{bool}}<br/>        
    <button ng-click="bool = !bool">Toggle Bool</button>
    {{a}}
    <div style="background-color:red" ng-mouseover="hover()">
        Hover here to trigger digest
    </div>
</div>

JS:

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {    
    $scope.bool = true; 
    $scope.a = 0;
    $scope.ternaryTrue = function(){
        console.log("ternary executed on true");   
    }
    $scope.ternaryFalse = function(){
        $scope.a++; //creates an infinite digest loop
        console.log("ternary executed on false");   
    }    
    $scope.hover = function(){
        console.log("Hover");
    }
}

The result is that the ternary operator is executed on EVERY digest.

Edit: An infinite digest loop can easily be created with this. As soon as something in the $scope will be changed during the function which is called by the ternary operator another digest will be started wich executes the function of the ternary operator again etc.

Related