How can I clear all the AngularJS $scope and $root

2020-08-17 18:26发布

问题:

I need to clear all the $scope values while performing some operations.

For eg: If I Click a "Signout" button to redirect to "signin" page, then all the $scope or $rootScope values in the session should be cleared.

How can I achieve this?

回答1:

You can do the following:

$rootScope = $rootScope.$new(true);
$scope = $scope.$new(true);

The function $new is creating a new scope inheriting the variables from the parent. true prevents the inheritance.

But this is not the correct approach, because if you use the thing above, you should bootstrap the controllers functions manually and recreating the tree of scopes.

This might be useful though, where the idea is to store the initialized data is stored in some variables and then, when assigned copied to the displayed variables.

The correct solution is to clear manually every property in each scope on the logout event like this: Logout event:

$rootScope.$broadcast("logout");

Catching the event:

$rootScope.$on("logout", function(){
      $rootScope.myData = undefined;
});

Or as suggested in the comments, to use a service and then be cleaned.



回答2:

               You not want delete scope 
               var authScope =['authLogo','currentPath','pageTitle','app'];                       
                for (var prop in $rootScope) {
                    if (prop.substring(0,1) !== '$') {
                        if(authScope.indexOf(prop) ==-1)
                            delete $rootScope[prop];
                    }
                }