angularjscontrollerrootscope

Passing data from one controller through another through $rootScope


I am beginning my development in angular and I don't know much. What I'm trying to do is that I am trying to pass a fairly large collection of data from one controller to another. This is how I managed to do it.

angular.module("myApp").controller("controllerName", function($rootScope, $scope, *...other stuff...*) 
{ /* code */ }

Later there is one specific method which is accessed from outside, and I copy the collection like this:

$rootScope.selectedItems = angular.copy($scope.selected.items);

(This is an array of 5k strings)

Which is then catched in another controller. Other developers said it is unsafe to pass this through $rootScope but after the data is passed and copied into local controller, I use this to get rid of the collection in rootScope

delete $rootScope.selectedItems;

Is this a safe way to do this? It works perfectly, and nothing seems dangerous to me


Solution

  • As a general rule, don't use $rootScope to pass data. By using it you make your module dependent on unspecified functionality which may not be a dependency of your module. It's a structural issue which will create problems later.

    Instead, use a service:

    angular.module("myApp").service("myAppService", function () {
        this.selectedItems = [];
    });
    
    angular.module("myApp").controller("controllerName1", function(myAppService, $scope) {
        $scope.selectedItems = myAppService.selectedItems;
    });
    
    angular.module("myApp").controller("controllerName2", function(myAppService, $scope) {
        $scope.selectedItems = myAppService.selectedItems;
    });
    

    It's also recommended that all your logic goes into services (and factories/providers where appropriate). Controllers should be used only to expose service functionality, unless a necessary special case can be proven. This makes the logic in services easier to unit test.