SO question. Unbind document click handler with Angular $onDestory

http://stackoverflow.com/questions/40723808/how-to-deregister-click-listener-in-angular-component/40723914

by HoffZ

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<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>

CSS

my-component {
  background-color: red;
}

JavaScript

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