0
votes

Angular docs on scope state:

At the end of $apply, Angular performs a $digest cycle on the root scope, which then propagates throughout all child scopes. During the $digest cycle, all $watched expressions or functions are checked for model mutation and if a mutation is detected, the $watch listener is called.

I wonder why does every $apply call a $digest on root scope? Wouldn't it be sometimes possible to detect which scope was modified and call $digest only on that scope and it's descendants.

For example take that controller and a view:

angular.module("aModule")
    .controller("aController", function($scope) {
        $scope.increase = function() {
            $scope.aValue += 1;
        };
    });


<div ng-controller="aController">
    <button ng-click="increase()">Increase</button>
</div>

Would clicking the button really run $digest loop on the root scope? Why not run it only on aController scope and it's descendants?

1
Because angular can't posibly know what you're doing in your function. What if it did instead $rootScope.aValue += 1? What if it modified the state of an object that is referenced by the root scope, or any other scope? - JB Nizet
because it is easy to start firing from $rootScope? - YOU
@JBNizet: I think I understand. What I haven't noticed is that AngularJS can't know what happens inside any function body; no matter if it's a controller body or third party code. It can never detect which scope values were modified. BTW you can post your comment as an answer and I'll accept it. - Robert Kusznier

1 Answers

1
votes

Because angular can't know what you're doing in your function.

It can instead do $rootScope.aValue += 1. Or it can modify the state of an object that is referenced by the root scope, or any other scope.