HoffZ HoffZ - 11 days ago 6
AngularJS Question

How to deregister click listener in Angular component?

How do I get rid of a document click listener when an Angular component is destroyed?

Simplified demo code:

<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

When clicking the button "Destroy component", the component gets removed from the DOM (with ng-if) and $onDestroy is triggered. I want the $onDestroy to deregister the click event, but nothing happens.

Answer

You should pass function reference to on & off method as in parameter. You don't need to pass whole click function reference.

Code

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 Here

Comments