how to broadcast and emit events to other controllers in angular that have no parent-child relationship

790 views Asked by At

I am trying to get hints from this post - Working with $scope.$emit and $scope.$on but nothing seems to work when the controllers are in no way related to each other.

That is -

<div ng-controller="CtrlA">
</div>

<div ng-controller="CtrlB">
</div>

and in CtrlB I would do something like this:

$rootScope.$broadcast('userHasLoggedIn', {})

and in CtrlA I would listen like so:

$rootScope.$on('userHasLoggedIn, function(event, data){});

And no - CtrlA never receives the broadcasted event unless I nest CtrlB div inside CtrlA div

Any idea?

1

There are 1 answers

0
Joao Leal On

It is tough to answer without knowing what you tried. Please see this plnkr: http://plnkr.co/edit/hYzWOrgEyPLlCMZnDCo2?p=preview

I basically created two controllers, one sends some text to the other:

app.controller('CtrlA', function($scope, $rootScope) {
  $scope.submit = function(){
    $rootScope.$broadcast('userHasLoggedIn', $scope.input);
  }

});

app.controller('CtrlB', function($scope) {
  $scope.$on('userHasLoggedIn', function(event, data){
    $scope.data = data; 
  });

  $scope.data = 'nothing';
});