【问题标题】:element.on($destroy) shows element is not defined in angularelement.on($destroy) 显示元素未以角度定义
【发布时间】:2015-09-30 18:28:38
【问题描述】:

我试图在更改应用程序的路由或状态时取消指令中的 $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)

提前致谢 代码很长,所以把sniper贴在被调用的地方。 更新:

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

【问题讨论】:

  • 代码在控制器内function Controller($scope, $interval){ //element.on($destroy) } 好吧,我试过这样做function($scope, $interval, element),但这是返回on is not defined
  • 你需要使用$scope.on('$destroy', ..
  • 是的,我也试过了,它返回了$scope.on is not defined
  • 你确定吗?您使用哪个 Angular 版本?
  • 我已经在我的项目中安装了 bower 组件。

标签: angularjs jqlite


【解决方案1】:

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

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

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

【讨论】:

  • 是的,刚才我在角度文档中找到了。谢谢:)
  • 经验教训我希望在问题中提供所有相关代码....避免很多混乱和cmets...祝你好运
  • 是的 Charlietfl!很抱歉!
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 2018-09-18
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 2015-07-02
  • 2017-07-09
  • 1970-01-01
相关资源
最近更新 更多