kiran Gopal kiran Gopal - 8 days ago 6
AngularJS Question

adding controller specific document eventlistener in angular

I am developing a web application for conducting the online quiz. I am using the mean stack for this. In my online test controller, I have used many event listeners such as

document.addEventListener("visibilitychange", onchange);
document.webkitIsFullScreen etc..


But my problem is this function still executing after moving to other controllers Because this is global eventLisners.

Can anyone suggest me best approach for this?

Answer

You need to remove the event listener when the scope is destroyed or as you put it 'after moving to other controllers':

$scope.$on('$destroy',function() {
   document.removeEventListener('visibilitychange',onchange);
});

Its always a good idea to handle the removal of event listeners when a component is destroyed, especially for large applications, as this can be a major cause of memory leak issues for single page applications.