问题描述
在执行某些操作时,我需要清除所有 $scope
值.
I need to clear all the $scope
values while performing some operations.
例如:如果我单击 "Signout"
按钮以重定向到 "signin"
页面,则所有 $ scope 或 $ 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值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!