Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 842
Gnik Avatar asked Apr 23 '15 08:04

Gnik


People also ask

What is $rootscope in AngularJS?

Typically, it acts as a glue between controller and view. Scopes are hierarchical in nature and follow the DOM structure of your angular app. AngularJS has two scope objects: $rootScope and $scope. Let's have a look, how they work.

What is scope in AngularJS?

Understanding Angularjs $.. Scope is an object that refers to the application model. It acts as a context for evaluating expressions. Typically, it acts as a glue between controller and view. Scopes are hierarchical in nature and follow the DOM structure of your angular app. AngularJS has two scope objects: $rootScope and $scope.

What is the use of $rootscope?

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.

What happens when a scope is destroyed in angular?

Just before a scope is destroyed, a $destroyevent is broadcasted on this scope. Application code can register a $destroyevent handler that will give it a chance to perform any necessary cleanup. Note that, in AngularJS, there is also a $destroyjQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.


1 Answers

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.

like image 99
Michael Avatar answered Sep 17 '22 13:09

Michael