km6zla
km6zla

Reputation: 4887

What is wrong with these $scope events suing $broadcast and $emit?

What I want is for SubCtrl to broadcast an event when it is loaded saying that it wants to get information. I want MainCtrl to be listening for a call to the get event and respond by broadcasting the 'set' event and providing its name property as an argument. The SubCtrl should be listening for the set event and respond by populating its own scopes name property.

With the following code, MainCtrl receives the get event, but SubCtrl never receives the set event.

Script

app.controller('MainCtrl', function($scope, $rootScope) {
  $scope.name = 'World';
  $scope.$on('get', function(event) {
    console.log('get event received');
    $rootScope.$broadcast('set', $scope.name);
  })
});

app.controller('SubCtrl', function($scope, $rootScope) {
  $scope.name = '..waiting';
  $rootScope.$broadcast('get');
  $scope.$on('set', function(event, name) {
    console.log('set event received');
    $scope.name = name;
  });
});

Markup

<body>
  <p ng-controller="MainCtrl">Hello {{name}}!</p>
  <p ng-controller="SubCtrl">Hello {{name}}!</p>
</body>

Upvotes: 0

Views: 191

Answers (2)

glepretre
glepretre

Reputation: 8167

Using $rootScope.$broadcast could be performance greedy depending on the size of your app. (See this question for more info.)

If you want to communicate between controllers on sibling nodes, there are 2 ways:

  • use a common parent controller
  • use a shared service.

With my team, we decided to develop a small pub/sub service to solve a similar issue. If you want to try it, here's our angular-pubsub service.

Upvotes: 1

km6zla
km6zla

Reputation: 4887

Once again I immediately realized the problem. I need to set the $on listener before I $broadcast the get event.

app.controller('SubCtrl', function($scope, $rootScope) {
  $scope.name = '..waiting';
  $scope.$on('set', function(event, name) {
    console.log('set event received');
    $scope.name = name;
  });
  $rootScope.$broadcast('get');
});

Upvotes: 0

Related Questions