locked
$scope.$apply in AngularJS? RRS feed

  • Question

  • User665472878 posted

    I don't understand how to use $scope.$watch and $scope.$apply. The official documentation isn't helpful.

    What I don't understand specifically:

    • Are they connected to the DOM?
    • How can I update DOM changes to the model?
    • What is the connection point between them?

    I tried this tutorial, but it takes the understanding of $watch and $apply for granted.

    What do $apply and $watch do, and how do I use them appropriately?

    Wednesday, May 9, 2018 6:44 PM

Answers

  • User-1134632663 posted

    You need to be aware about how AngularJS works in order to understand it.

    Digest cycle and $scope

    First and foremost, AngularJS defines a concept of a so-called digest cycle. This cycle can be considered as a loop, during which AngularJS checks if there are any changes to all the variables watched by all the $scopes. So if you have $scope.myVar defined in your controller and this variable was marked for being watched, then you are implicitly telling AngularJS to monitor the changes on myVar in each iteration of the loop.

    A natural follow-up question would be: Is everything attached to $scope being watched? Fortunately, no. If you would watch for changes to every object in your $scope, then quickly a digest loop would take ages to evaluate and you would quickly run into performance issues. That is why the AngularJS team gave us two ways of declaring some $scope variable as being watched (read below).

    $watch helps to listen for $scope changes

    There are two ways of declaring a $scope variable as being watched.

    1. By using it in your template via the expression <span>{{myVar}}</span>
    2. By adding it manually via the $watch service

    Ad 1) This is the most common scenario and I'm sure you've seen it before, but you didn't know that this has created a watch in the background. Yes, it had! Using AngularJS directives (such as ng-repeat) can also create implicit watches.

    Ad 2) This is how you create your own watches. $watch service helps you to run some code when some value attached to the $scope has changed. It is rarely used, but sometimes is helpful. For instance, if you want to run some code each time 'myVar' changes, you could do the following:

    function MyController($scope) {
    
        $scope.myVar = 1;
    
        $scope.$watch('myVar', function() {
            alert('hey, myVar has changed!');
        });
    
        $scope.buttonClicked = function() {
            $scope.myVar = 2; // This will trigger $watch expression to kick in
        };
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 9, 2018 6:47 PM