Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use $rootScope on Angularjs?

Tags:

angularjs

If the right way to share data between controllers are using factory/service, what is the purpose of the $rootScope?

like image 808
Julio Marins Avatar asked Feb 28 '16 23:02

Julio Marins


People also ask

What is $rootScope in AngularJS?

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.

When would you use a $rootScope?

$rootScope exists, but it can be used for evilScopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.

How many $rootScope an AngularJS application can have?

The scope in AngularJS is hierarchical in nature: The $rootScope acts as a global variable. All the $scopes of an AngularJS application are children of the $rootscope. An app can have only one $rootScope.

What is difference between $scope and $rootScope object?

$rootscope is available globally (for all Controllers), whereas $scope is available only to the Controller that has created it. Don't get confused by this statement.


2 Answers

$rootScope exists, but it can be used for evil

Scopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.

Occasionally there are pieces of data that you want to make global to the whole app. For these, you can inject $rootScope and set values on it like any other scope. Since the scopes inherit from the root scope, these values will be available to the expressions attached to directives like ng-show just like values on your local $scope.

Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.

Conversely, don't create a service whose only purpose in life is to store and return bits of data.

-- AngularJS FAQ

like image 115
georgeawg Avatar answered Sep 17 '22 05:09

georgeawg


As per my understanding. you can use $rootScope in multiple places .

  • global settings defined in factory and then in view you can update as per your condition. f.x layout manipulation
  • you can assigned $state on run.
  • you can handle error ($rootScope.$on(...)

I hope this will help.

Thanks

like image 27
nikudale Avatar answered Sep 21 '22 05:09

nikudale