How to reset $rootScope?
Asked Answered
Z

3

8

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?

Zetland answered 18/6, 2015 at 4:51 Comment(0)
L
9

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() {
    ...
}
Let answered 18/6, 2015 at 5:8 Comment(0)
B
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 
Bolding answered 18/6, 2015 at 4:56 Comment(1)
This no longer seems to be the case as of 1.6 github.com/angular/angular.js/blob/v1.6.x/src/ng/…Rhiana
L
2

To delete a variable from rootScope

delete $rootScope.variablename
Laskowski answered 18/6, 2015 at 4:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.