Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset $rootScope?

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?

like image 755
Adam Boostani Avatar asked Jun 18 '15 04:06

Adam Boostani


3 Answers

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() {
    ...
}
like image 88
soote Avatar answered Oct 19 '22 17:10

soote


  • 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 
like image 21
Ramesh Rajendran Avatar answered Oct 19 '22 18:10

Ramesh Rajendran


To delete a variable from rootScope

delete $rootScope.variablename
like image 23
Sajeetharan Avatar answered Oct 19 '22 19:10

Sajeetharan