Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS doesn't scroll to top after changing a view [duplicate]

Tags:

angularjs

For example:

A user scrolls down on view A;

Then the user clicks on a link, which takes the user to view B;

The view is changes, but the user's vertical location remains lthe same, and must scroll manually to the top of the screen.

Is it an angular bug?

I wrote a small workaround that uses jquery to scroll to the top; but I don't find the correct event to bind it to.

edit after seeing the comment:

How and WHEN do i pull myself to the top? i'm using jquery but the $viewContentLoaded event is too soon (the method runs, but the page doesn't scroll at that time)

like image 516
Berry Tsakala Avatar asked Jun 01 '14 14:06

Berry Tsakala


2 Answers

The solution is to add autoscroll="true" to your ngView element:

<div class="ng-view" autoscroll="true"></div>

https://docs.angularjs.org/api/ngRoute/directive/ngView

like image 74
Adriano Resende Avatar answered Sep 25 '22 11:09

Adriano Resende


Angular doesn't automatically scroll to the top when loading a new view, it just keeps the current scroll position.

Here is the workaround I use:

myApp.run(function($rootScope, $window) {

  $rootScope.$on('$routeChangeSuccess', function () {

    var interval = setInterval(function(){
      if (document.readyState == 'complete') {
        $window.scrollTo(0, 0);
        clearInterval(interval);
      }
    }, 200);

  });
});

Put it in your bootstrap (usually called app.js).

It's a pure javascript solution (it's always better not to use jQuery if it's easy).

Explanation: The script checks every 200ms if the new DOM is fully loaded and then scrolls to the top and stops checking. I tried without this 200ms loop and it sometimes failed to scroll because the page was just not completely displayed.

like image 26
Guilhem Soulas Avatar answered Sep 21 '22 11:09

Guilhem Soulas