Search code examples
angularjsangularjs-scopeangularjs-events

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


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


Solution

  • 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