AngularJS Is it possible to listen to $destroy in another controller?

654 Views Asked by At

In my application, When a controller is being destroyed, is it possible to the $destroy event it emits in another controller?

1

There are 1 best solutions below

0
maurycy On BEST ANSWER

You can use a factory/service to register callback that would be called on controller destruction

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, notifyService) {
  $scope.logs = []
  notifyService.callback = function(){
    $scope.logs.push('controller destroyed on: ' + new Date().toString())
  }
});

app.controller('directiveController', function($scope, notifyService){
  $scope.$on('$destroy', notifyService.callback)
})

app.service('notifyService', function(){
  this.callback = angular.noop
})

app.directive('toggleDirective', function(){
  return {
    template: "<div>I'm directive with controller that will be destroyed</div>",
    controller: 'directiveController'
  }
})

http://plnkr.co/edit/ZJ2sbJSOyYZyQxAWzOxS?p=preview