What $ apply & $ digest functions are in angularjs and its use

angular What is the difference between $ apply and $ digest functions can anyone explain this exact usage of uses, digest function and difference in angular and what scenario we can use this function

//digest function
$scope.$digest();

//apply function like this         
$scope.$apply(function(scope)
{
    scope.demo = "angular";
});
     (or)
//apply function like this
$scope.$apply(function()
{
    $scope.demo = "angular";
});

      

can anyone explain this exact use of the applicable, digest functions and angle difference, and what scenario we can use these functions.

+3


source to share


3 answers


TL; DR

  • $scope.$digest()

    : starts a digest cycle on $scope

    and on children.
  • $scope.$apply(expr)

    : evaluates expr

    and starts the digest cycle at $rootScope

    .

It is not recommended to refer to $scope.$digest()

(unless you really know what you are doing) because it will not propagate changes outside the $scope

subtree.




Very shortly (because there are many resources (post, tutorial, etc.) explaining the depth differences):




$scope.$digest();

      

Starts a digest cycle on $scope

, i.e. evaluates watch expressions of observers $scope

and its children, and performs watch-actions as needed. This cycle is repeated as many times as necessary until all values ​​stabilize (subject to the digest ttl limit ).




$scope.$apply(expr);

      

Parses expr

and evaluates it in context $scope

. Then it calls $rootScope.$digest()

, which basically evaluates the observers of everyone in the application (since each area is a child $rootScope

).

Parsing expr

(using $parse

) results in (more or less) results in a function that, when called with a context as an argument (for example, scope), returns the evaluation result expr

in that context. Angular will call this function passing in $scope

as a context. If it is expr

already a function, there is no need to actually parse it (again, this can be simplified a bit, but applicable to most cases). Another thing to note is that executing the code internally $apply()

catches errors and then goes through $exceptionHandler

(which is an added bonus).

Some examples:

// Let there be Scopes...
var scope1 = $rootScope.$new();
var scope2 = $rootScope.$new();
var scope2_1 = scope2.$new();

// Let there be watchers...
$rootScope.$watch(/* RootWatcher */);
scope1.$watch(/* Scope1Watcher */);
scope2.$watch(/* Scope2Watcher */);
scope2_1.$watch(/* Scope2_1Watcher */);

// Let there be `$digest`s...
$rootScope.$digest();   // Evaluates ALL watchers
scope1.$digest();       // Evaluates ONLY Scope1Watcher
scope2.$digest();       // Evaluates BOTH Scope2Watcher, Scope2_1Watcher
scope2_1.$digest();     // Evaluates ONLY Scope2_1Watcher

// Let there be `$apply`s...
$rootScope.$apply();          // Runs $rootScope.$digest()
scope1.$apply();              // Still runs $rootScope.$digest()
scope1.$apply('test = 42');   // Boils down to: scope1.test = 42
    // ...and is equivalent to:
    scope1.$apply(function (scope) { scope.test = 42; });
    // ...which in turn is equivalent to:
    scope1.$apply(function (ignored) { scope1.test = 42; });

// So, I could have a reusable function:
var assign42 = function (scope) { scope.test = 42; };
scope1.$apply(assign42);     // Boils down to: scope1.test = 42;
scope2.$apply(assign42);     // Boils down to: scope2.test = 42;
scope2_1.$apply(assign42);   // Boils down to: scope2_1.test = 42;

      

Another notable thing about it $apply()

is that it catches errors and passes them to Angular's $ exceptionHandler (which is good). For example:.

// BAD - Avoid doing this:
somePossiblyErrorThrowingFunc();
scope.$apply();

// GOOD - Do this instead:
scope.$apply(somePossiblyErrorThrowingFunc);

      




Needless to say, Angular (if used correctly) will handle the digest lifecycle for you, so you don't have to manually call $digest()

/ $apply()

. The exceptions are event handlers associated with DOM elements and callbacks in third-party code that runs outside of the Angular context. This is also well documented in the docs: $ digest , $ apply

0


source


This step, which checks if any binding values ​​have changed, has a method $scope.$digest()

. In fact, when the magic happens, but we almost never call it directly, instead we use $scope.$apply()

which will call $ scope. $ Digest () for you.

$scope.$apply()

takes an Angular function or expression string and executes it, then calls $scope.$digest()

to update any bindings or observers.

So when do you need to call $ apply ()?



Very rare, in fact. AngularJS actually calls almost all of your code in $ apply call. Events like ng-click

controller initialization, callbacks are $http

wrapped in $scope.$apply()

. So you don't need to call it yourself, in fact you cannot. Calling $apply

inside $ apply will result in an error.

You need to use it if you are going to run the code on a new turn. And only if this twist is not generated from a method in the AngularJS library. Inside this new twist, you should wrap your code in $scope.$apply()

. Here's an example. We are using setTimeout which will execute the function in a new mode after a delay. Since Angular is unaware of this new twist, the update will not be reflected.

function Ctrl($scope) {
  $scope.message = "Waiting 2000ms for update";

    setTimeout(function () {
        $scope.$apply(function () {
            $scope.message = "Timeout called!";
        });
    }, 2000);
}

      

0


source


$ digest ()

  • The $scope.$digest()

    function iterates over all the clocks in the $ scope object and its $ scope objects (if any). When $digest()

    iterating over the watch, it calls the value function for each watch movement. If the value returned by the value function is different from the value it returned the last time it was called, the listener function for that clock is called.

  • The function $digest()

    is called whenever it AngularJS

    thinks it is necessary. For example, after executing a button click handler or after an AJAX call (after executing the done () / fail () callback function).

  • You might run into some corner cases where AngularJS doesn't call the $ digest () function for you. You will usually find this by noticing that data bindings do not support display values. In this case, call $ scope. $ Digest () and it should work. Or perhaps you can use $ scope. $ Apply () instead, which I'll explain in the next section.


$ apply ()

  • The function $scope.$apply()

    takes a function as a parameter, which is executed and then $scope.$digest()

    called internally. This will make it easier for you to check all clocks and thus all data bindings are updated. Here's an example $apply()

    :

    $scope.$apply(function() { $scope.data.myVar = "Another value"; });

  • The function passed to the function $apply()

    as a parameter will change the value $scope.data.myVar

    . When the function exits AngularJS

    , the $ scope function is called. $ Digest (), so all watches are checked for changes in observed values.

Link to

-1


source







All Articles