angularjsrootscopeangularjs-rootscope

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?


Solution

  • 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() {
        ...
    }