Ivo
Ivo

Reputation: 1673

AngularJS service rootscope

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?

Upvotes: 2

Views: 6103

Answers (3)

Mark Rajcok
Mark Rajcok

Reputation: 364697

$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!)

Upvotes: 5

Caio Cunha
Caio Cunha

Reputation: 23394

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>​

Upvotes: 1

jaime
jaime

Reputation: 42031

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.

Upvotes: 1

Related Questions