Search code examples
javascriptangularjsangularjs-directivengrouteng-view

Event listeners fired multiple times from same directive


In my app I am using a custom directive with a window resize event listener:

link: function(scope, elem, attrs) {
    angular.element($window).bind('resize', function() {
        // viewId is a unique reference to the view in which the directive lives
        console.log(scope.viewId);
    });
}

This directive is inserted 1 or multiple times in each of my views.

What puzzles me is why the function is executed not only for the active view, but also for inactive ones. This happens once I have accessed more than one view.

What puzzles me even more, is why the function is called multiple times from the same view, after I have visited the same view multiple times.

It seems to me that the old directive scope is not destroyed, but kept alive and a new scope is created on top of the old one.

Is there anything I can do to prevent this behavior?


Below a code snippet of the working solution based on the answer provided by Renan Lopes Ferreira (I am using LoDash _.debounce to prevent the function being called too often):

windowResize = _.debounce(function () {
    // My logic
    $scope.$apply();
}, 150);

// Attach debounced function to the window.resize event listener
angular.element($window).on('resize', windowResize);

// Remove the function when the directive is destroyed
$scope.$on('$destroy', function () {
    angular.element($window).off('resize', windowResize);
});

Solution

  • You need to remove the listener when your directive is destroyed. Something like:

    angular.element($window).on('resize', resize);
    
    scope.$on('$destroy', function () {
      angular.element($window).off('resize', resize);
    });
    
    function resize(){
        ...
    }