E
E
Egor2015-02-10 17:15:27
JavaScript
Egor, 2015-02-10 17:15:27

How to remove $rootScope.$on listener in Angularjs?

Greetings.
Listening to the event for $rootScope in the directive. An element with a directive can disappear and reappear on the page. Each time the visibility changes, a listener for $rootScope is added. As a result, when the event is raised, the handler is called multiple times.
What is the correct way to remove $rootScope.$on in Angularjs? Now I'm using $rootScope.$$listener, but the documentation says that you shouldn't use private fields.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Dedukhin, 2015-02-10
@ByKraB

The moment of deleting an element is tracked as follows:

var deregFunc = $rootScope.$on('someEvent', function() {});
scope.$on('$destroy', function() {
  deregFunc();
});

D
DigitalSmile, 2015-02-10
@DigitalSmile

https://docs.angularjs.org/api/ng/type/$rootScope.Scope

$on
...
Returns
function() 	

Returns a deregistration function for this listener.

But I would advise you to use $rootScope less often, over time it can turn into a "global variable" antipattern. It is better to use services as common components for several modules.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question