AngularJS: Global Variables Sharing between Controllers

We have got basically 2 options for “global” variables:

1. $rootScope

$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. Every application has a single root scope. All other scopes are descendant scopes of the root scope. Using the $rootScope is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.

Example of AngularJS “global variables” using $rootScope:

Controller 1 sets the global variable:

Controller 2 reads the global variable:

Here is a working jsFiddle: http://jsfiddle.net/natefriedman/3XT3F/1/

$rootScope exists, but it can be used for evil (http://docs.angularjs.org/misc/faq)

Scopes in Angular form a hierarchy, prototypically 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.

2. Services

Services are singletons that you can inject to any controller and expose their values in a controller’s scope. Services, being singletons are still ‘global’ but you’ve got far better control over where those are used and exposed.

Using services is a bit more complex, but not that much, here is an example:

and then in a controller:

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/

Resource: Stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA