Auzy
Auzy

Reputation: 2155

Delaying Angular Directive Execution

What would be the best way to delay this directive running? I have a small delay between states that needs to be waited out prior to directives execution or else it will mess up the scroll. I have attempted to use $timeout but seem to be using it wrong as it throws errors...

app.directive('scrolltop', function() {
    return {
        restrict: 'A',
        link: function(scope, element) {
            element.on('click', function() {
                console.log('scrolltop');
                $('html, body').animate({
                    scrollTop: $(element).offset().top - 50
                }, 2000);
            });
        },
    }
});

Upvotes: 0

Views: 369

Answers (1)

Oleksandr Pyrohov
Oleksandr Pyrohov

Reputation: 16276

I wrote a simple example using $timeout (scroll down the div and click on the background).

HTML:

<div ng-app="TestDebounce">
    <div scrolltop class="scrolltop">
        <span>...</span>
    </div>
</div>

Angular directive:

(function() {
    angular.module('TestDebounce', []).directive('scrolltop', scrolltop);
    scrolltop.$inject = ['$timeout'];

    function scrolltop($timeout) {
        return {
            restrict: 'AE',
            link: linkFunction
        }

        function linkFunction(scope, element) {
            element.on('click', function() {
                $timeout(function() {
                    $('html, body').animate({
                        scrollTop: $(element).offset().top - 50
                    }, 'fast');
                }, 2000); // 2 seconds timeout
            });
        }
    }

}());

JS fiddle link - try it.

Upvotes: 1

Related Questions