1

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

R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • 1
    Possible duplicate of [Share data between AngularJS controllers](https://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers) – Aleksey Solovey Mar 08 '18 at 11:09
  • You have both the [tag:angular] and [tag:angularjs] tags in your question. They are *generally* mutually exclusive: angularjs is used for the 1.x version, angular is used for all the other versions. Since the reply may be version dependent, you may want to specify the actual version you are using. – SPArcheon Mar 08 '18 at 11:16

2 Answers2

0

There are many service are available you should go with broadcast

Here is example for $broadcast service https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Santosh Singh
  • 561
  • 2
  • 16
0

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.

Shoreline
  • 798
  • 1
  • 9
  • 26