如何在单个函数中清除所有AngularJS $ scope和$ rootScope值? [英] How can I clear all the AngularJS $scope and $rootScope values within a single function?

查看:272
本文介绍了如何在单个函数中清除所有AngularJS $ scope和$ rootScope值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如:如果我单击 "Signout" 按钮以重定向到 "signin" 页面,则所有 $ scope 或<应该清除会话中的strong> $ rootScope 值.

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.

我该如何实现?

推荐答案

您可以执行以下操作:

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

函数$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");

赶上活动:

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

或者按照注释中的建议使用服务,然后将其清除.

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

这篇关于如何在单个函数中清除所有AngularJS $ scope和$ rootScope值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆