Tuesday, December 17, 2013

Global variables in AngularJS:

You've got basically 2 options for "global" variables:
$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. 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.
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:
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
  return {
      name : 'anonymous'
  };
});
and then in a controller:
function MyCtrl($scope, UserService) {
    $scope.name = UserService.name;
}

Example of AngularJS "global variables" using $rootScope:
Controller 1 sets the global variable:
function MyCtrl1($scope, $rootScope) {
    $rootScope.name = 'anonymous'; 
}
Controller 2 reads the global variable:
function MyCtrl2($scope, $rootScope) {
    $scope.name2 = $rootScope.name; 
}
See http://jsfiddle.net/natefriedman/3XT3F/1/
   http://jsfiddle.net/3XT3F/10/

No comments:

Post a Comment