AngularJS是否可以在另一个控制器中监听$ destroy?

时间:2017-04-28 10:02:25

标签: angularjs angularjs-scope angularjs-events

在我的应用程序中,当一个控制器被销毁时,是否有可能在另一个控制器中发出$ destroy事件?

1 个答案:

答案 0 :(得分:1)

您可以使用工厂/服务来注册将在控制器销毁上调用的回调

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