Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Supposed I have a controller for a page that is being rendered into an ng-view.

This controller binds to some events of an external source (such as an application-wide message bus) to update its model. This basically works very easy:

function MyController ($scope) {
  $scope.bar = '…';

  externalSource.on('foo', function (data) {
    $scope.$apply(function () {
      $scope.bar = data.bar;
    });
  });
}

The problem is: How do I unbind the controller from the external source once the view it it is associated with is not longer shown?

Is there something such as a dispose event or something similar?

Or is my approach completely wrong, and I should deal with something like that somehow else? If so, how?

like image 388
Golo Roden Avatar asked Mar 17 '13 11:03

Golo Roden


2 Answers

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

like image 91
Dmitry Evseev Avatar answered Oct 22 '22 04:10

Dmitry Evseev


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 ....
  });
like image 26
Stewie Avatar answered Oct 22 '22 02:10

Stewie