10

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?

Gnik
  • 101
  • 1
  • 1
  • 3
  • Here you can find some methods to achieve that: http://stackoverflow.com/questions/13085024/reset-a-model-with-angular-js – frhd Apr 23 '15 at 08:06
  • @frhd. Thanks its clear. Using this example we can clear $scope values in the particular controller. But I want to clear all the $scope values in all the controllers during signout. Is it possible? If yes, give me you suggestion/solution.. – Gnik Apr 23 '15 at 08:10
  • I don't think there is a one-liner-kind-of way to clear all the scopes. As written here http://stackoverflow.com/a/18527334/2491198, you would need to notify all scopes to delete their data. One way to avoid having to do that, is storing the data in a **DataService** and clearing that on logout. – frhd Apr 23 '15 at 08:16
  • I dont know if you have heard of Ionic Framework. But they do have a similar function where you just call the ` $ionicHistory.clearCache(); $ionicHistory.clearHistory(); ` Maybe read the source code for this? – Karan Kumar Dec 30 '15 at 06:20

2 Answers2

16

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.

Michael
  • 3,308
  • 5
  • 24
  • 36
0
               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];
                    }
                }