Logan
Logan

Reputation: 2515

$rootScope.$on not getting called after broadcast

I have two controllers and want to notify one controller that some event has happened from the other controller. For this I am trying to use angular broadcast but have been unsuccessful. Please find below my code:

firstController.js

 $rootScope.$on('xyz',function(){
    alert('Called');
 });

secondController.js

  $rootScope.$broadcast('xyz');

Can someone please help in identifying what I am missing here?

Upvotes: 1

Views: 1459

Answers (3)

sylwester
sylwester

Reputation: 16508

Please have a look here: jsfiddle

 var app = angular.module('app', []);

app.controller('c1', function($rootScope, $scope){

    $scope.click = function() {
         $rootScope.$broadcast('xyz');
    }
});

app.controller('c2', function($scope){

   $scope.$on('xyz', function(){

    alert("clicked");
    });

})

Upvotes: 1

Josh Beam
Josh Beam

Reputation: 19812

Use either a combination of:

$rootScope.$broadcast();
$scope.$on();

// or

$rootScope.$emit();
$rootScope.$on();

$broadcast dispatches the event downward to all child scopes, so you can listen to it with the $scope service.

However, $emit dispatches upward through the scope hierarchy, and since $rootScope is the at the highest level, you can use $rootScope to dispatch and listen to the same event. This is also much better in regards to performance since the event doesn't propagate down through multiple scopes.

Upvotes: 1

sylwester
sylwester

Reputation: 16508

in firstController.js use $scope instead $rootScope

$scope.$on('xyz', function(event, args) {

   alert('Called')
});

Upvotes: 0

Related Questions