How to reset $rootScope?

11.6k views Asked by At

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?

3

There are 3 answers

0
soote On BEST ANSWER

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() {
    ...
}
0
Sajeetharan On

To delete a variable from rootScope

delete $rootScope.variablename
1
Ramesh Rajendran On
  • 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