简体   繁体   English

Angular的$ rootScope#$ digest

[英]Angular's $rootScope#$digest

Reading this excellent book ( Mastering Web Development in AngularJS ), I ran across this code: 阅读这本出色的书(《 AngularJS中的Mastering Web Development》 ),我遇到了以下代码:

var Restaurant = function ($q, $rootScope) {

var currentOrder;

this.takeOrder = function (orderedItems) {
    currentOrder = {
    deferred:$q.defer(),
    items:orderedItems
};
    return currentOrder.deferred.promise;
};
this.deliverOrder = function() {
    currentOrder.deferred.resolve(currentOrder.items);
    $rootScope.$digest();
};
this.problemWithOrder = function(reason) {
    currentOrder.deferred.reject(reason);
    $rootScope.$digest();
};

My understanding is that the $rootScope.$digest(); 我的理解是$rootScope.$digest(); calls are made in order to alert Angular that the Promise 's state has been updated. 进行调用是为了提醒Angular Promise的状态已更新。

Is my understanding correct? 我的理解正确吗? Also, is it necessary to make the above $rootScope.$digest(); 另外,是否需要使上面的$rootScope.$digest();成为必需$rootScope.$digest(); calls? 电话?

$scope.$digest() is what processes all of the $watch events that are on the current and children scope. $ scope。$ digest()是处理当前作用域和子作用域上的所有$ watch事件的处理方式。 It essentially manually tells the scope to check if a scope variable has changed. 它实际上是手动告诉作用域以检查作用域变量是否已更改。 You don't generally want to use this when you are inside of a controller or a directive, because the $scope.$apply() function calls the $digest anyway and it is called when you mutate a scope variable. 当您在控制器或指令内部时,通常不需要使用此函数,因为$ scope。$ apply()函数无论如何都会调用$ digest,并且在更改范围变量时会调用它。

Checkout this link for an example. 查看此链接以获取示例。

You don't need a $rootScope.$digest here .because resolving/rejecting the promise will fire a $rootScope.$digest internelly, as $intervel , $timeout , $http (after request finished) does that for you. 您在这里不需要$rootScope.$digest ,因为在内部解析/拒绝了诺言会触发$rootScope.$digest ,因为$intervel intervel, $timeout$http (在请求完成后)会为您执行此操作。 And this $digest can throw errors of $digest already in progress. 这个$ digest可能会引发已经在进行中的$ digest错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM