In my application, When a controller is being destroyed, is it possible to the $destroy event it emits in another controller?
Asked
Active
Viewed 641 times
0
-
can you not use any other custom event name other than `$destroy`? you are not wanting to listen to controller being destroyed anyway.. – tanmay Apr 28 '17 at 10:04
-
If it's not being destroyed I assume the $destroy event won't go off either... Soo.. No. – Tom Apr 28 '17 at 10:08
-
When a controller and it's scope is being destroyed it fires the $destroy event. What I was wondering is if I can listen to this $destroy event in another controller, that's all. – Maximillion Bartango Apr 28 '17 at 10:10
-
Just so I don't have to broadcast/emit an event manually in each controller. Just for efficiency. – Maximillion Bartango Apr 28 '17 at 10:12
-
I have edited the question. – Maximillion Bartango Apr 28 '17 at 10:15
-
Why do you want to do that? It looks like XY problem. – Estus Flask Apr 28 '17 at 13:02
-
The reason shouldn't be relevant, I was simply asking if it is possible. – Maximillion Bartango Apr 28 '17 at 13:47
1 Answers
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'
}
})

maurycy
- 8,455
- 1
- 27
- 44