Angularjs $broadcast once, $on twice

19.3k views Asked by At

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) {});
4

There are 4 answers

4
Tomas On BEST ANSWER

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) {});
0
que1326 On

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' )

0
Big Sam On

The only solution I could get to work was to create the listener inside the $viewContentLoaded event:

$scope.$on('$viewContentLoaded', function() {
  //Put your listener(s) in here
  $scope.$on('menuActivateActionPublish', function(event) {});
});
0
João Otero On

To complement que1326 answer, as an example, if you are using ui-router and have something like

.state('app.yourpage', {
            url:'yourPage',
            views: {
                'content@': {
                    templateUrl : 'views/yourPage.html',
                    controller  : 'YourController'
                }
            }
        })

and in yourPage.html you have a ng-controller="YourController as Ctrl", then you are creating 2 instances of the controller: 1 instance is created by the state configuration and another one in your html.