Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • AngularJS $apply

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 151
    Comment on it

    AngularJS $apply comes into play when it invokes digest cycle to watch the scope model changes. Angular wraps the function call within the $scope.$apply. It means it executes a complete new life cycle. If the execution of the function is normal, the changes are reflected in the view and gets updated.
      $apply works only around AngularJS context,i.e. the angularjs built-in directives do this automatically and reflects the changes we do into the view. But if the change is out of the AngularJS context,i.e if we use any 3rd party library, then we need to explicitly tell angular that some changes are done by wrapping our code into $apply function.
    For example-

    $scope.msgDisplay = function() {
            setTimeout(function() {
              $scope.$apply(function() {
                //wrapp this within $apply
                $scope.code = Checking updated message ;
                console.log(updated message:' + $scope.code);
              });
            }, 3000);
          }
          
          $scope.msgDisplay();


    HTML-

    <div ng-controller=sampleController>
           updated message: {{code}}
          </div>

              In the above code, we have wrapped our code within $apply. If we don’t do this, then the code message will get updated but it will not get reflected into the view because we have used javascript’s setTimeout function. Therefore, we need to manually use $apply function so that it triggers digest cycle and activates all the watchers and ensure the changes take effect. As a result the view gets updated in 3 seconds.

    Note:- Sometimes we may get error-‘$digest already in progress’ if we use $apply heavily. To resolve this, we use $timeout or $evalAsync.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: