如何在单个函数中清除所有AngularJS $ scope和$ rootScope值?

时间:2015-04-23 08:03:33

标签: angularjs angularjs-scope angular-ui-router angular-ui

我需要在执行某些操作时清除所有 $scope 值。

例如:如果我点击 "Signout" 按钮重定向到 "signin" 页面,那么所有 $ scope 。应清除会话中的strong>或 $ rootScope 值。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:16)

您可以执行以下操作:

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

函数$new正在创建一个继承父项变量的新范围。 true会阻止继承。

但这不是正确的方法,因为如果你使用上面的东西,你应该手动引导控制器功能并重新创建范围树。

This可能是有用的,其中的想法是存储初始化的数据存储在一些变量中,然后,当分配复制到显示的变量时。

正确的解决方案是在logout事件中手动清除每个范围内的每个属性,如下所示: 退出事件:

$rootScope.$emit("logout");

抓住活动:

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

或者按照评论中的建议,使用服务然后进行清理。

答案 1 :(得分: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];
                    }
                }