如何注销 Angular 组件中的点击监听器?

How to deregister click listener in Angular component?

如何在 Angular 组件被销毁时删除文档点击侦听器?

简化的演示代码:

<div ng-app="app">
  <div ng-controller="TestingCtrl as vm">

    <my-component ng-if="vm.showComponent"></my-component>

    <br><br><br>

    <button ng-click="vm.setShowState(false)">
      Destroy component
    </button>

  </div>
</div>

Javascipt:

angular.module('app', [])

.controller('TestingCtrl', function TestingCtrl() {
    this.showComponent = true;

  this.setShowState = function(state) {
    this.showComponent = state;
  }
})

.component('myComponent', {  
  bindings: {
    name: '@'
  },
  template: 'myComponent',  
  controller: function ($document) {
    var listener;

    this.$onInit = function() {
        listener = $document.on('click', function () {
            console.log('You clicked on the document');
        });
    }

    this.$onDestroy = function() {
        console.log('$onDestory triggered');
        $document.off('click', listener);
    }

  }
});

Fiddle

单击按钮 "Destroy component" 时,组件将从 DOM 中删除(使用 ng-if)并触发 $onDestroy。我希望 $onDestroy 取消注册点击事件,但没有任何反应。

您应该将函数引用作为参数传递给 on & off 方法。您不需要传递整个点击功能参考。

代码

this.$onInit = function() {
    listener = function () {
        console.log('You clicked on the document');
    };
    $document.on('click', listener); 
}

this.$onDestroy = function() {
    console.log('$onDestory triggered');
    $document.off('click', listener);
}

Demo Fiddle这里