admin管理员组文章数量:1316980
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?
3 Answers
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>
本文标签: javascriptAngularJS service rootscopeStack Overflow
版权声明:本文标题:javascript - AngularJS service rootscope - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742018920a2414298.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论