Reputation: 4887
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.
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;
});
});
<body>
<p ng-controller="MainCtrl">Hello {{name}}!</p>
<p ng-controller="SubCtrl">Hello {{name}}!</p>
</body>
Upvotes: 0
Views: 191
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:
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
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