如何重置 $rootScope?

How to reset $rootScope?

用户注销后,我需要清理我的 $rootScope。我尝试了 $rootScope.$destroy(),但没有成功。有没有一种方法可以遍历 $rootScope 中的所有值并删除它们,或者有一种方法可以简单地重置它?

从 rootScope 中删除一个变量

delete $rootScope.variablename
  • Indeed, the $destroy() method won't work on $rootScope (see here). I've worked around that by invoking $rootScope.$broadcast("$destroy") rather than .$destroy() when eliminating an entire Angular instance on our app. This way, all destructors are invoked the same.

  • As for the element $destroy event, I have to admit I wasn't even aware of it just a few days ago… I hadn't seen it anywhere in the docs, plus I'm using jQuery so according to here it wouldn't work for me anyway.

参考自here

那是很长的描述,但是您可以使用以下方法手动清除 RootScope

选项 1

清除 rootScope 变量

$rootScope.currentStatus = ""; //or undefined 

选项 2

如果你想删除整个 $rootscope 对象,

 $rootScope=undefined //or empty 

您可能希望在 $rootScope 初始化时保留默认值。由于它们都以 $ 开头,因此您可以删除所有不以 $.

开头的属性
for (var prop in $rootScope) {
    if (prop.substring(0,1) !== '$') {
        delete $rootScope[prop];
    }
}

您可以通过将其添加为 $rootScope 上的函数来使其更容易调用。

$rootScope.$resetScope = function() {
    ...
}