7

I am working on a single page app, with angular and I have a need to communicate between 2 different directives which basically don't have a parent child relation.

In Directive A, I have 2 places where I need to broadcast same event from different functions. And in Directive B, have written a $on listener for that.

Now, I observe that the whenever callFirstFunc & its broadcast is called for first time, the listener will be called once. Upon subsequent calling, the listener is called twice, thrice and so on ,it keeps on increasing.

The callSecondFunc is called when the callFirstFunc has been executed, so the listener for this is also called as many no. of times the listener for broadcast in callFirstFunc. So, why is the listener not called only once, why multiple times? It is looping and increasing every time.

Directive A:

app.directive("firstDir", function ($rootScope) {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            // some other code
            callFirstFunc();
            var callFirstFunc = function(){
                // some other code
                $rootScope.$broadcast("someEvent");
            }
            callSecondFunc();
            var callSecondFunc = function(){
                // some other code
                $rootScope.$broadcast("someEvent");
            }
        }
    };
});

Directive B:

app.directive("secondDir", function ($rootScope) {
        return {
            restrict: 'E',
            link: function (scope, element, attrs) {
                // some other code
                scope.$on("someEvent", function(){
                    detectSTuff();
                }) 
               function detectStuff(){
                  // other code
               }                    
            }
        };
    });
whyAto8
  • 1,660
  • 4
  • 30
  • 56
  • Possible duplicate of [AngularJs broadcast repeating execution too many times](http://stackoverflow.com/questions/19553598/angularjs-broadcast-repeating-execution-too-many-times) – kinkajou Jan 18 '17 at 01:30

2 Answers2

1

I think you forgot to unbind the even handler.

You can do it like following -

var someEventHandle = scope.$on("someEvent", function(){
                    detectSTuff();
                });
scope.$on('$destroy', someEventHandle);
Rabi
  • 2,210
  • 17
  • 18
  • 4
    Rabi - I tried, but its still the same. Its listening more than once and keeps on increasing. – whyAto8 Nov 06 '14 at 17:55
0

This code works for me:

$rootScope.$$listeners.nameOfYourEvent.length = 1;
Walter White
  • 976
  • 4
  • 12
  • 29