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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With