Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs $broadcast once, $on twice

Tags:

It sends $broadcast once from the rootScope, but the listener ($on) gets called twice.

The listener is in a controller and it uses $rootScope.$on instead of $scope.$on. Has someone had this problem?

edit

rootScope:

$rootScope.$broadcast('menuActivateAction' + item.event_name_postfix, item.event_args);

other Controller:

$rootScope.$on('menuActivateActionPublish', function(event) {});
like image 314
Shai M. Avatar asked Jun 21 '15 20:06

Shai M.


2 Answers

Since you register your $on listener on $rootScope, it doesn't get destroyed with the controller and next time you init the controller it gets created again.

You should create your listener on controller scope

$scope.$on('menuActivateActionPublish', function(event) {});
like image 61
Tomas Avatar answered Oct 22 '22 09:10

Tomas


Be careful you avoid two instances of the controller means two event listeners, which means the method gets executed twice !! ( example: using twice 'ng-controller' )

like image 43
que1326 Avatar answered Oct 22 '22 10:10

que1326