Angular - translation, $ on call several times in the directive

I am working on a one-page application with angular, and I need to communicate between two different directives, which basically do not have a parent relationship with children.

In directive A, I have 2 places where I need to broadcast the same event from different functions. And in directive B they wrote $ lister for this.

Now I notice that whenever a callFirstFunc and its translation is called for the first time, the listener will be called once. After a subsequent call, the listener is called twice, thrice, etc., It continues to increase.

The callSecondFunc call is called when callFirstFunc is executed, so the listener is also called as many as not. times listener for broadcast in callFirstFunc. So why the listener is not called only once, why several times? It is cyclical and increases 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 } } }; }); 
+6
source share
2 answers

I think you forgot to untie the even handler.

You can do it as follows -

 var someEventHandle = scope.$on("someEvent", function(){ detectSTuff(); }); scope.$on('$destroy', someEventHandle); 
+1
source

This code works for me:

 $rootScope.$$listeners.nameOfYourEvent.length = 1; 
0
source

Source: https://habr.com/ru/post/977819/


All Articles