How to unbind an external event when a controller/$scope is destroyed? How to unbind an external event when a controller/$scope is destroyed? angularjs angularjs

How to unbind an external event when a controller/$scope is destroyed?


To execute event unbind when controller's scope is got destroyed use:

$scope.$on('$destroy', function () { /* Unbind code here */ });

See Scope docs for more info


Use $routeChangeStart or $routeChangeSuccess events:

function MyController ($scope) {  $scope.bar = '…';  externalSource.on('foo', function (data) {    $scope.$apply(function () {      $scope.bar = data.bar;    });  });  $scope.$on('$routeChangeStart', function(next, current){    // unregister listener    // externalSource.off ....  });}

... or $destroy event:

  $scope.$on('$destroy', function(){    // unregister listener    // externalSource.off ....  });