0

Let's say I have two pages, page A and page B, which have controller A and controller B, respectively. I go to page A first, and do an operation, which would call $broadcast to send out one object:

$rootScope.$broadcast('payData', obj)

I want to receive this broadcast in controller B. But since I have not gone to page B, the constructor of controller B is not initialized. Since I try to receive this message in the constructor of controller B, it never receives the message.

export default class ControllerB{
    constructor($scope, $rootScope){
        this.scope = $scope;
        this.rootScope = $rootScope

        $rootScope.$on('payData', (event, obj) => {
            console.log('broadcastPayData receive obj:', obj);
        })
    }
    //some other cool staff
}

Any idea how to solve this? Thanks.

Setily
  • 814
  • 1
  • 9
  • 21
Benjamin Li
  • 1,687
  • 7
  • 19
  • 30
  • 1
    You should store the `payData` in a service. Using events won't work if the controllers aren't going to be active at the same time (and they're generally very fragile anyway). – Joe Clay Sep 22 '16 at 09:11
  • @JoeClay, smart, good idea! thanks – Benjamin Li Sep 22 '16 at 09:18

1 Answers1

0

If controller B doesn't exist yet, it would make sense to just save the object to rootScope and B will access it once it's loaded:

$rootScope.payData = obj

Then just use it in your controllerB

export default class ControllerB{
    constructor($scope, $rootScope){
        this.scope = $scope;
        this.rootScope = $rootScope

        console.log($rootScope.payData);
    }
    //some other cool staff
}

You can also watch the $rootScope.payData if it can change over time.

Martin Gottweis
  • 2,721
  • 13
  • 27
  • 1
    Using `$rootScope` to share data between controllers tends to be pretty unmaintainable in the long run. This is why Angular has services - to contain logic/data that should be shared around the application. – Joe Clay Sep 22 '16 at 09:17
  • @JoeClay Sure, using a service is a great idea – Martin Gottweis Sep 22 '16 at 09:38