mfrachet
mfrachet

Reputation: 8922

Remove event listener when $scope is destroy

I m actually facing a problem.

I have a directive that listens on an event like :

$scope.$on('event',myFunc);

The problem is that when the controller is destroyed, the $scope keeps the event listener alive..

What code should I put in

$scope.$on('$destroy',myDestroyFunc);

to prevent this effect ?

Thanks for advance

Upvotes: 0

Views: 773

Answers (2)

bahadir
bahadir

Reputation: 719

you should listen for scope destroy event and deregister from event on destroy. $on returns a deregister function for events.

var deregister = $scope.$on('event',myFunc);
$scope.$on('$destroy', deregister);

Upvotes: 1

top.dev
top.dev

Reputation: 457

Just save reference to your event and use it in $destroy

var myFuncEvent = $scope.$on('event', myFunc);
$scope.$on('$destroy', myFuncEvent);

Upvotes: 0

Related Questions