How to avoid $on getting triggered multiple times while navigating from one tab to another in angularJs?

Viewed 25

I have gone through all the available solutions to avoid $on getting triggered multiple time but nothing works for me. I want to understand where I am going wrong. I have two tabs, one is home and another is reports. Both have different controllers but one directive from where functions are getting called via $broadcast.

If I am using $rootScope.$broadcast and $rootScope.$on, it is working fine while I load the home page but when I navigate from reports tab to home tab that time $rootScope.$on is getting fired many times.

Please help me fix this issue.

Here is the code:

myApp.controller('homeCtrl', function($scope, $rootScope) {
   $rootScope.$broadcast('prodDetails');
});

myApp.controller('reportsCtrl', function($scope, $rootScope) {
   $rootScope.$broadcast('prodDetails');
});

myApp.directive('commDirective', ['$rootScope', function($rootScope){
    return {
        restrict: 'A',
        replace: true,
        scope: {
            onCallback: "="
        },
        controller: ['$scope',function($scope) {
            $rootScope.$on("prodDetails", function(event) {
                console.log("test");
            });
        }],
    };
}]);
0 Answers
Related