[英]Stop event listeners on '$destroy'. TypeError: $on is not a function;
I'm trying to stop all event listeners while scope is destroyed. 我试图在范围被破坏的同时停止所有事件监听器。
I get this error: 我收到此错误:
TypeError: vm.$on is not a function;
Neither vm.on(..) works 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.');
})
}
The problem is that vm
doesn't have the $on(...
declared, you must use $scope
instead. Inject it on your controller and declare like $scope.$on
. 问题是
vm
没有声明$on(...
,您必须使用$scope
。将其插入控制器并像$scope.$on
一样声明。
When using controllerAs
syntax, this very often missunderstood that you shouldn't use $scope
at all. 当使用
controllerAs
语法时,这常常被人误解为根本不应该使用$scope
。 However, the recomendation is to avoid using $scope
for certain activities not abolish it from your controller. 但是,建议您避免在某些活动中使用
$scope
而不从控制器中取消它。 Scope always will exists, it's an internal of your controller, just don't use it like a view model, but you can use it anyways for such tasks like, listen to events, broadcast, emmit, etc. 范围将始终存在,它是控制器的内部组件,只是不要像视图模型那样使用它,但是无论如何,您都可以使用它来执行诸如侦听事件,广播,发送等任务。
Try something like (after you've injected $scope
on your dependencies): 尝试类似的事情(在对依赖项注入
$scope
之后):
$scope.$on('$destroy', function() {
vm.stop();
console.log('DashboardController scope destroyed.');
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.