AngularJS Broadcast does not work with loading the first controller

In this PlunkerDemo, I am trying to pass an event from the parent controller to the child controller. However, you cannot do this directly in the parent controller. The handler does not register the event. However, this is done based on ng-click or based on setTimeout, it works. Is this related to the life cycle of a sphere?

http://beta.plnkr.co/edit/ZU0XNK?p=preview

See comments on accepted answer. They explain my problem.

+4
source share
2 answers

Any changes in the angular area should be made within the angular framework, if any changes should be made outside the framework, we should use . $ apply .

$ apply () is used to execute an expression in angular from outside the angular frame.

In your case, you call $ broadcast in setTimeout where the callback is called outside the angular scope.

So, you have two solutions: either use the $ timeout service provided by angular, or use . $ apply .

I prefer to use the $timeout function.

 var ParentCtrl = function($scope, $rootScope, $timeout){ $scope.broadcast = function(){ $rootScope.$broadcast('Sup', 'Here is a parameter'); }; $timeout(function(){ $scope.$broadcast('Sup'); }, 1000); //this one does not work! Most likely due to scope life cycle $scope.$broadcast('Sup'); $scope.$on('SupAgain', function(){ console.log('SupAgain got handled!'); }); }; 

Demo: Fiddle

Using $apply

 setTimeout(function(){ $scope.$apply(function(){ $scope.$broadcast('Sup'); }); }, 1000); 
+17
source

A more reliable option would be to use $ interval in the child controller. Thus, instead of a significant timeout, each small interval will be polled. Alternatively, use the flag service instead of broadcasting. Each poll will check if the flag is set. When the flag is set by the parent controller, the timer will stop during the next polling. And this may mean that an event has occurred. The parent controller can also communicate with the child controller through the service.

0
source

All Articles