How to reset $ rootScope?

After the user logs out, I need to clear my $ rootScope. I tried $rootScope.$destroy() but that didn't help. Is there a way to iterate over all the values ​​in $ rootScope and delete them, or is the method just reset it?

+8
angularjs rootscope angularjs-rootscope
source share
3 answers

You might want to keep the default values ​​that come with $rootScope when it is initialized. Since they all start with the $ character, you can remove all properties that don't start with $ .

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

You can simplify the call by adding it as a function to $rootScope .

 $rootScope.$resetScope = function() { ... } 
+9
source share
  • Indeed, the $destroy() method will not work on $ rootScope (see here ). I worked on this by calling $rootScope.$broadcast("$destroy") rather than .$destroy() when excluding the entire Angular instance in our application. Thus, all destructors are called the same way.

  • Regarding the event of the $ destroy element, I have to admit that I didn’t even know about it just a few days ago ... I did not see it anywhere in the documents, plus I use jQuery according to here , it still will not work.

Link from here

This is a long description, but you can manually clean RootScope using the following methods

Option 1

Clear rootScope variable

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

Option 2

if you want to remove whole $ anchop objects,

  $rootScope=undefined //or empty 
+4
source share

To remove a variable from rootScope

 delete $rootScope.variablename 
+2
source share

All Articles