Search code examples
angularjsrootscope

can controllers create arbitrary properties in the $rootScope in Angular


Is it legal for a controller to do something like this in Angular?

       $rootScope.someArbitaryObject = ["fee", "fie", "fo", "fum];

or

      $rootScope.foo = {name: "Jane Q. Public", favoriteColor: "green"}

Solution

  • Yes, it is legal but only if you want ALL controllers to have access to that model.

    A better practice is to use services that you can then inject to one or more controllers:

    var myApp = angular.module('myApp', []);
    
    myApp.factory('MyService', function () {
      return { message: "I'm data from a service" };
    });
    
    myApp.controller('FirstCtrl', function($scope, MyService) {
      $scope.data = MyService;
    });
    
    myApp.controller('SecondCtrl', function($scope, MyService) {
      $scope.data = MyService;
    });
    

    Any change you make to MyService properties in one controller will affect all the other controllers that use MyService.