8

用户注销后,我需要清理我的 $rootScope。我试过$rootScope.$destroy()了,但这并没有奏效。有没有办法遍历 $rootScope 中的所有值并删除它们或简单地重置它的方法?

4

3 回答 3

9

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

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

您可以通过将其作为函数添加到$rootScope.

$rootScope.$resetScope = function() {
    ...
}
于 2015-06-18T05:08:45.207 回答
4
  • 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.

Reference from here

That is long description, But you can manually clear the RootScope by using this below ways

Option 1

Clear the rootScope variable

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

Option 2

if you want to remove whole $rootscope objects,

 $rootScope=undefined //or empty 
于 2015-06-18T04:56:00.963 回答
2

To delete a variable from rootScope

delete $rootScope.variablename
于 2015-06-18T04:54:39.403 回答