9951 explained code solutions for 126 technologies


angularjsHow do I create and access a global variable in AngularJS?


Creating and accessing global variables in AngularJS is pretty straightforward. To create a global variable, you just need to create a variable inside the $rootScope object. For example:

$rootScope.myGlobalVariable = 'Hello World';

To access the global variable, you can use $rootScope.myGlobalVariable in any controller, directive, or service.

Code explanation

  • $rootScope: The $rootScope is the parent scope of all other scopes in AngularJS. It is the highest level scope and can be accessed from any other scope.
  • myGlobalVariable: This is the name of the global variable.
  • 'Hello World': This is the value of the global variable.

Helpful links

Edit this code on GitHub