0

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

Maximillion Bartango
  • 1,533
  • 1
  • 19
  • 34

1 Answers1

1

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

maurycy
  • 8,455
  • 1
  • 27
  • 44