2

I have a service defined in AngularJS with app.factory("serviceName", function($rootScope) { .. }) If I do $rootScope.$apply(), would that re-evaluate ALL the controller's scopes in the app or just the scopes of the controllers which use this service?

3 Answers 3

5

$digest() only "flushes" the current scope and all of its child scopes.

$apply(exp) evaluates the exp and then calls $digest() on the root scope. So calling $apply() (on any scope) affects all scopes.

If you call $digest() and your action changes some parent scope, the change will not be observed. So normally you want to call $apply(). (If you're tempted to try and be more efficient by calling $digest(), it can bite you later!)

Sign up to request clarification or add additional context in comments.

1 Comment

digest is really what I needed. I have always used $apply with the idea that it affects only the current scope.
1

There's only one root scope per application. Calling $rootScope.$apply() will trigger a digest cycle that will dirty check the entire scope tree.

To avoid this, call $apply from the controller's scope or its parent scope if you want to dirty-check multiple sibling scopes.

1 Comment

I think you meant to say $digest in the 2nd paragraph.
1

The code below will log MyCtrl and MyCtrl2 to the console every two seconds, suggesting that any $apply to any $scope, will digest all scopes. The question is against which scope the applied function will run. If it dirty check only the applied scope, the MyCtrl shouldn't be logged. Fiddle here.

var mod = angular.module('MyApp', []);

mod.controller('MyCtrl', function($scope) {
    $scope.value = function() {
        console.log('MyCtrl');
        return 'value';
    };

    setInterval(function() {
        $scope.$apply()
    }, 2000);
});

mod.controller('MyCtrl2', function($scope) {
    $scope.value2 = function() {
        console.log('MyCtrl2');
        return 'value 2';
    };
});​
<div ng-app="MyApp">
  <div ng-controller="MyCtrl">{{value()}}</div>
  <div ng-controller="MyCtrl2">{{value2()}}</div>
</div>​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.