Pankaj Parkar Pankaj Parkar - 1 year ago 124
Javascript Question

How to put listen over $destroy while using controllerAs syntax in angular

Now I'm getting rid of

dependency from my angular controller to ensuring that I could easily migrate my code to Angular2. My current angular version is
While doing the same thing there is place while I placed
listener over my controller scope like
$scope.$on('$destory', function() ....)

I can see
method only available on
of controller, but how can I achieve it without using

Answer Source

If you are using angular 1.5+ they added lifecycle hooks that you can opt into on your controller. No $scope needed. Just add a function called $onDestroy() to your controller and it will be called when your controller is being clean up:

$onDestroy() - Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, watches and event handlers.

Example from

function MyCmpController($element) {

  var clickHandler = function () {
    // do something

  this.$onInit = function () {
    $element.on('click', clickHandler);

  this.$onDestroy = function () {
    $'click', clickHandler);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download