-1

我试图在更改应用程序的路由或状态时取消指令中的 $interval 事件。我发现这段代码可以在破坏事件中起作用。

但这会返回我的元素未定义。我是否必须在控制器中注入任何服务或指令。

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

错误:

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)

在此先感谢 代码很长,所以在调用的地方发布了狙击手。更新:

   (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); 
     });
4

1 回答 1

0

当一个新的路由被初始化时,使用$scope.$on('$destroy'..)和间隔定时器将被移除:

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

在上面的评论中,尝试使用$scope.on()不正确,因为所有角度内部事件方法都使用$前缀

于 2015-09-30T18:49:17.040 回答