anoop
anoop

Reputation: 3822

angularjs1.5+ component doesn't receive broadcast event ($on doesn't work)

I was writing some code and realized that angularjs1.5+ component doesn't actually receive the $scope.$broadcast event, means $scope.$on never run in component controller function.

Though I was able to $emit the event from the component controller and received by the parent controller by $on, but it just doesn't listen for the broadcast event.

broadcast from parent: $scope.$broadcast('parentEvnt', [1,2,3]);

but NOT recieved in component : $scope.$on('parentEvnt', function(event, data){ \\

I created this plunker to show the issue.

Searched some articles and as well on SO but didn't found any answer, and tried with $rootScope.$broadcast that didn't help too.

and, If it is not possible, then what's the best way to notify the component from any random place in app?

Upvotes: 1

Views: 770

Answers (1)

tanmay
tanmay

Reputation: 7911

The problem here is you are broadcasting the event even before your child controllers initialize and start listening to those event. Hence, it doesn't matter whether you use $scope or $rootScope to broadcast :)

For instance, I changed your broadcast to have it inside a $timeout with 2 seconds, it would work as expected.

$timeout(function() {
  $rootScope.$broadcast('parentEvnt', [1,2,3]);
}, 2000);

Though, you would ideally want to have it on button click or some other scenario.

working example

Upvotes: 3

Related Questions