angularjs

How does $scope.apply() work exactly in AngularJS?


I often updated model variables corresponding to DOM expression ({{}}) within the controllers. e.g.

$scope.myVar = new_value;

Some times the corresponding DOM expression {{myVar}} is updated automtically, others it's not.

I understand that sometimes we need to call $scope.$apply but...

Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.6/$rootScope/inprog?p0=%24digest

Any clue?


Solution

  • Apply essentially "refreshes" your front end with the changes that had occurred to your scope.

    Most of the time you don't need to do apply as it already is done for you.

    Let's say that you do an ng-click(); Apply is done for you.

    However, there are cases where apply is not triggered, and you must do it yourself.

    Example with a directive:

     .directive('someCheckbox', function(){
       return {
         restrict: 'E',
         link: function($scope, $el, $attrs) {
           $el.on('keypress', function(event){
             event.preventDefault();
             if(event.keyCode === 32 || event.keyCode === 13){
               $scope.toggleCheckbox();
               $scope.$apply();
             }
           });
         }
       }
     })
    

    I have made changes to my scope but no apply was done for me thus I need to do it myself.

    Another example with a timeout:

    $scope.getMessage = function() {
      setTimeout(function() {
        $scope.message = 'Fetched after two seconds';
        console.log('message:' + $scope.message);
        $scope.$apply(); //this triggers a $digest
      }, 2000);
    };
    

    Understanding apply and digest