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

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

问题描述

我需要在执行某些操作时清除所有 $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.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

您可以执行以下操作:

$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天全站免登陆