Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangularjs-service

The use of 'global' variables on AngularJS


Ok, I went into a heated argument with a colleague about the way of properly using global variables on AngularJS. Here's his reasoning: there's many ways to "do" things.

Consider this:

var app = angular.module('myApp', []);

app.globalVar = []; // this is just to store same data later

Then on some directive/service:

app.directive('myDirective', function(){
    app.globalVar = [23,43,21]; // populating from a json or other source
});

app.directive('myDirective2', function(){
    var x = app.globalVar;
});

I think this is bad but I would like to know, from a technical view, why this is wrong and what's the proper use of 'global' variables in AngularJS.

I read about using $rootScope and I also read somewhere that on version 2.0 AngularJS is dropping $scope altogheter so maybe the only way will be using a service/factory?


Solution

  • In general I do not use global variables. They pollute the window scope and can make your code more confusing. For an example like the one you gave I would recommend using a factory or a service to persist the data. Then you can inject it clearly into whatever controller/direct/other-service that you want. While your co-worker is correct that there are many ways to do things I do not recommend polluting the global scope.

    app.
     module('myApp')
     .factory('myFactory', myFactory);
    
    function myFactory() {
      var globalVar = [23,43,21];
    
      return {
        get: function() {
          return globalVar;
        }
      }
    }
    

    and then in your controller(or whatever)

    app.
      module('myApp')
      .controller('MyCtrl', MyCtrl);
    
      function MyCtrl(myService) {
        var localVar = myService.get();
      }