angularjsdom-eventsngroute

$viewContentLoaded gets triggered multiple times in Angular ngRoute application


I have a pretty straight forward set up two tabs, home and admin:

  $routeProvider
             // route for the home page
             .when('/home', {
             templateUrl : 'views/home.html',
             controller  : 'myCtrl',
             controllerAs: 'vm',
             resolve:{
                 loadDropDowns:function(DataSvc,$rootScope){
                    
                        return DataSvc.GetDropDowns();
                    
                 }
             }
         })
         // route for admin page
         .when('/admin',{
             templateUrl : 'admin/templates/admin.html'             
         })

and in the controller, I have a listener for $viewContentLoaded event like so:

$rootScope.$on('$viewContentLoaded', function(event){
        console.log(" viewContentLoaded fired ");
      });

And every time I click on the home tab, the event handler firings double so first time its 2 , than 4 , than 8 and so on...

I have another event broadcasted when the drop downs are loaded, and for one brodcasted event, I get multiple firings of the handler as well.

 $rootScope.$broadcast('dropDownsSet');

and in the same controller :

    $rootScope.$on('dropDownsSet', function(event, mass) {}

gets executed multiple times as well.. ( same as above, every time doubling the number of times the event handler firing)

I'm at my wits end, what could be the cause for this madness?


Solution

  • Move event binding code

    $rootScope.$on('$viewContentLoaded', function(event){
      console.log(" viewContentLoaded fired ");
    });
    

    from myCtrl controller to some main application (parent) controller. What happens now is that every time you navigate to Home tab, myCtrl gets instantiated, thus registering one more event listener on the $rootScope.