How can I clear all the AngularJS $scope and $rootScope values within a single function?

狂风中的少年 提交于 2020-01-02 01:12:09

问题


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];
                    }
                }


来源:https://stackoverflow.com/questions/29817252/how-can-i-clear-all-the-angularjs-scope-and-rootscope-values-within-a-single-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!