How to reset $rootScope?

感情迁移 提交于 2019-12-10 12:52:08

问题


After user logs out, I need to clean up my $rootScope. I tried $rootScope.$destroy() but that didn't do the trick. Is there a way to loop through all the values in $rootScope and delete them or a method to simply reset it?


回答1:


You may wish to retain the default values that come with $rootScope when it is initialized. Since they all begin with a $ you can delete all the properties that don't start with $.

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

You could make it easy to call by adding it as a function on $rootScope.

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



回答2:


  • 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 



回答3:


To delete a variable from rootScope

delete $rootScope.variablename


来源:https://stackoverflow.com/questions/30906669/how-to-reset-rootscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!