最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS service rootscope - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Dec 16, 2012 at 23:43 IvoIvo 1,6733 gold badges19 silver badges28 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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!)

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.

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>​
发布评论

评论列表(0)

  1. 暂无评论