Search code examples
angularjsjqlite

element.on($destroy) shows element is not defined in angular


I am trying to cancel the $interval event in my directive while changing the route or state of the application. I found this code which could act in destroy event.

But this returns my element is not defined. Do I have to inject any service or directive in the controller.

element.on('$destroy', function() {
          console.log("cancelling interval");
          $interval.cancel(promise);
        });

Error:

ReferenceError: element is not defined
    at new Controller (http://localhost:port/src/controller.js
    at invoke (http://localhost:port/bower_components/angular/angular.js:4182:17)
    at Object.instantiate (http://localhost:port/bower_components/angular/angular.js:4190:27)
    at http://localhost:port/bower_components/angular/angular.js:8453:28
    at $interpolate.compile (http://localhost:port/bower_components/angular-ui-router/release/angular-ui-router.js:3897:28)
    at invokeLinkFn (http://localhost:port/bower_components/angular/angular.js:8217:9)
    at nodeLinkFn (http://localhost:port/bower_components/angular/angular.js:7726:11)
    at compositeLinkFn (http://localhost:port/bower_components/angular/angular.js:7075:13)

Thanks in advance Code is pretty long, so posting the snipper where is called. Updated:

   (function ()
   { 
   'use strict'; 
   angular .module('app')
   .controller('Controller', Controller); 
   Controller.$inject = ['Service', '$modal', '$interval', '$scope']; 
   function Controller(Service, $modal, $interval, $scope)
   { 
     console.log("Beginning");
     var ctrl = this;
     $scope.headerName= "Header Name";
     ctrl.selected = {};
     setupData(); 
     var promise = $interval(setupData, 1000000);
     $scope.on('$destroy', function()
     { 
     $interval.cancel(promise); 
     });

Solution

  • Use $scope.$on('$destroy'..) and the interval timer will be removed when a new route is initialized:

    $scope.$on('$destroy', function() {
          console.log("cancelling interval");
          $interval.cancel(promise);
    });
    

    WIthin the comments above the attempt at using $scope.on() was incorrect as all angular internal events methods use $ prefix