nehalist nehalist - 5 months ago 30
AngularJS Question

Angular controller lifetime and event handling

How to handle events (like

$rootScope
or socket events) in an Angular controller correctly? I'm facing the problem that my controllers aren't destroyed, which cause some problems when it comes to listening to specific events.

To make it clear what I mean here's a plunker: http://plnkr.co/edit/CkXKUnpUdsbnZEjq8zLy?p=preview

Triggering the rootscope event (by clicking on the button) in the first place works as intended: just one event is fetched. But navigating to
Route 2
and triggering the rootscope event again shows my problem; the event is fetched twice, since (at least that's my guess) both controllers are active now. Every route switch causes an additional event listener.

How to handle this?

Answer

Use $scope.$on instead of $rootScope.$on, the listeners will be destroyed on scope destruction automatically.