3

I needed to add an event listener into an Angular application. An external plugin is listening that event to trigger some action.

I did that :

$window.addEventListener('itemLoaded', itemLoaded, false);

It works but I don't find a way to remove that event when I change my state (I use ui-router).

Do you know a better way into Angular to add that event and remove it, if my state change ?

Thanks for your help.

David Dias
  • 312
  • 3
  • 14

2 Answers2

3

If this code is being called inside of a controller, you could listen for a $scope.$destroy() event and then remove the listener when the controller unloads.

// Inside some controller
var listener = function listen() {...};
var element = document;

element.addEventListener('click', listener)

$scope.$on('$destroy', function(event, object) { 
    element.removeListener('click', listener);
})

here's the plnkr example

4UmNinja
  • 510
  • 4
  • 14
  • Yes, I'm calling that into a controller. Can you please write me the code to remove that event? I tried the 'removeEventListener()' but its seems not working... – David Dias Apr 19 '16 at 07:47
  • 1
    there's good mention of it here .. [stack post](http://stackoverflow.com/questions/14416894/provide-an-example-of-scopes-destroy-event). You might have to attach you "itemLoaded" function to the controllers scope and then remove it by name inside of that $destroy event. this is the best i could come up with for now .. [plnkr](http://plnkr.co/edit/gosqMH7abdQXAOUTOJZd?p=info) – 4UmNinja Apr 19 '16 at 08:13
  • 1
    ` $scope.$on('$destroy', function(e){ $window.removeEventListener('itemLoaded', itemLoaded); }); ` Works perfectly :) – David Dias Apr 19 '16 at 10:09
0

If you are using ui-router you can check the current state with $state.current.url. If the current url changes you can remove the event. You can even use $watch in the routing file to check whether state changed or not

Syam Pillai
  • 4,967
  • 2
  • 26
  • 42