1

The question is fairly self explanatory.

If I open a web socket connection in an Angular JS via a controller, it will remain open after navigation (route change).

This is normal behaviour of course, but I was wondering what might be the "best practice" way to request the connection be closed upon navigation.

I could obviously hook in to the $routeChange... methods and broadcast to the controller. But am I missing something? Is there a better way?

LiverpoolsNumber9
  • 2,384
  • 3
  • 22
  • 34

1 Answers1

3

Listen for the $destroy event on your controller's $scope and clean up everything that needs cleaning up, in your case that would be closing the websocket connections.

$scope.$on('$destroy', function(event) {
    ...
});

Some more background on the lifecycle of angular controllers can be found in this answer.

Community
  • 1
  • 1
ivarni
  • 17,658
  • 17
  • 76
  • 92