nehalist nehalist - 1 year ago 95
AngularJS Question

Angular controller lifetime and event handling

How to handle events (like

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:

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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download