Directive is executed 2 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 code above does is to execute the function "onResizeFunction" every time the window is resized.

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

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

asked by anonymous 12.03.2015 / 19:08

1 answer

1

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

One way 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 resize event occurs after 100 milliseconds.

Sample source: link

    
12.03.2015 / 20:05