0

我試圖在範圍被銷燬時停止所有事件監聽器。

我得到這個錯誤:

TypeError: vm.$on is not a function; 

無論vm.on(..)的作品

angular.module('app.layout') 
     .controller('DashboardController', DashboardController); 

     DashboardController.$inject = ['$interval','dataservice']; 


     function DashboardController($interval, dataservice) { 
     var vm = this; 
     vm.name = "DashboardController"; 


     console.log('Init Dashboard Controller'); 
     initEvents(); 
/* 
... 
*/ 

    ///////////////////////////// 

    function initEvents() { 
      vm.$on('$destroy', function() { 
      vm.stop(); 
      console.log('DashboardController scope destroyed.'); 
      }) 
     } 
+0

'vm'是一個控制器,不是範圍。這是您需要注入'$ scope'服務的情況。 – Claies

+0

我不是AngularJS的傢伙,但是$是$ scope方法... –

回答

3

的問題是,vm沒有$on(...聲明,您必須使用$scope代替。將其注入控制器並聲明爲$scope.$on

使用controllerAs語法時,經常會誤解您根本不應該使用$scope。但是,建議避免將$scope用於某些活動,而不是從控制器中取消它。範圍總是會存在的,它是你的控制器的內部,只是不使用它就像一個視圖模型,但你可以用它來處理諸如事件,廣播,發送等事件。

試一下(在您的依賴關係中注入$scope之後):

$scope.$on('$destroy', function() { 
    vm.stop(); 
    console.log('DashboardController scope destroyed.'); 
})