Search code examples
javascriptangularjsscrollng-animate

How to smooth scroll with ngAnimate?


I am wondering why inside my controller this does not work:

angular.module('app', [
        'ngAnimate',
    ])
    .controller('MainCtrl', function ($scope, $log, $window, $document) {
        var scrollTop = 200 // For example
        angular.element(document).find('body').animate({scrollTop: scrollTop}, 'slow');

    });
});

I am just trying to scroll smoothly to a specific offset to the top of the body tag. Do I have to use the ngAnimate in a different way?

TypeError: angular.element(...).find(...).animate is not a function


Solution

  • ngAnimate does not have anything to do with .animate(). This function is related to jQuery and not to AngularJS. So a working solution will look like this:

    angular.module('app', [
            'ngAnimate',
        ])
        .controller('MainCtrl', function ($scope, $log, $window, $document) {
            var scrollTop = 200 // For example
            $('html, body').animate({scrollTop: scrollTop}, 'slow');
    
        });
    });
    

    Also do not forget to load jquery in your html file before you load the script above.