Angular takes care of cleaning up after itself, most of the time. For example, if you use
$scope.$on('someEvents', handleSomeEvent);
, the event will be automatically removed when the scope is destroyed (e.g. when navigating to a different page or view in your app).
However, it's important to remember that $rootScope
is never destroyed unless you close your app. So if you use
$rootScope.$on('someEvents', handleSomeEvent);
, you may need to manually remove the event listener, depending on where you are listening for the event:
- If you are in a
controller
or directive
, you will need to remove the event listener yourself. Otherwise, every time you instantiate the controller, a new event listener will be attached, leading to multiple calls to handleSomeEvent
.
- If you are in a
service
, you do not need to remove the event listener manually, as services are always singletons (it's worth noting that in Angular, services, factories, etc., all essentially serve the same purpose).