Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS + Safari: Force page to scroll to top when pages switch

I am having an odd, safari-only scrolling behavior using AngularJS.

Whenever the user flips between pages, the pages are being changed as if they are AJAX. I understand they are in AngualrJS, but the resulting behavior is that the browser does not scroll to top when the user switches pages.

I've tried to force the browser to scroll to top whenever a new controller is being used, but it does not seem to do anything.

I'm running the following JS at the top of every controller:

document.body.scrollTop = document.documentElement.scrollTop = 0;

This is also a Safari-only bug, every other browser will scroll to top when the page changes. Has anyone encountered a similar issue or think of a better way to resolve it?

like image 253
Neil Avatar asked Aug 13 '13 20:08

Neil


3 Answers

$window.scrollTo(0,0) will scroll to the top of the page.

I just found a nice plugin (pure angularJS) that supports animations also:

https://github.com/durated/angular-scroll

like image 89
Alex C Avatar answered Sep 27 '22 21:09

Alex C


you can use this:

.run(["$rootScope", "$window", '$location', function($rootScope, $window,  $location) {

    $rootScope.$on('$routeChangeStart', function(evt, absNewUrl, absOldUrl){
        $window.scrollTo(0,0);    //scroll to top of page after each route change
}}])

or for tab switches you can use the $window.scrollTo(0,0); in your controller

like image 39
danikoren Avatar answered Sep 27 '22 20:09

danikoren


Have you tried using $anchorScroll()? it's documented here.

like image 24
The WebMacheter Avatar answered Sep 27 '22 21:09

The WebMacheter