Directive is executed 2 times

Asked

Viewed 186 times

0

I have the following "directve":

app.directive('modal', ['$window', function ($window) {
return {
    restrict: 'C',
    link: function (scope, element, attrs) {
        scope.onResizeFunction = function() {
            console.log(attrs.id);
        };

        scope.onResizeFunction();
        angular.element($window).bind('resize', function() {
            scope.onResizeFunction();
            scope.$apply();
        });
    }
}
}]);

What the above code does is perform the "onResizeFunction" function every time the window is resized.

Inside the function I have "console.log" which traces the element ID.

When resize the window, the ID appears 2 times in a row, that is, the function is executed 2 times, even if there is only 1 element in the HTML with the class "modal", where the "Directive" is applied.

1 answer

1

Different browsers interpret the event of resize in different ways. Some trigger an event before starting the resize; other, each window event that transforms the viewport; others, only when the event is finalized - and several implement a mix of the three.

One of the ways to avoid these continuous shots is to filter events according to a time window:

var res;
window.onresize=function() {
    if (res){clearTimeout(res)};
    res = setTimeout(function(){console.log("resize triggered");},100);
};

In this code snippet, console.log will only be invoked if no other event of resize happen after 100 milliseconds.

Example source: https://stackoverflow.com/questions/15812618/window-onresize-fires-twice

Browser other questions tagged

You are not signed in. Login or sign up in order to post.