AngularJS does not scroll up after changing view

For instance:

The user views view A;

Then the user clicks on a link that allows the user to view B;

The view is a change, but the custom vertical layout remains the same and must be scrolled manually at the top of the screen.

Is this an angular bug?

I wrote a small workaround that uses jquery to scroll up; but I did not find the correct event to associate it with.

change after viewing the comment:

How and WHEN do I keep myself on top? I use jquery, but the $ viewContentLoaded event is too early (the method is executing, but the page is not scrolling at this time)

+6
source share
3 answers

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

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

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

+20
source

Angular does not automatically scroll at the top when loading a new view, it just keeps the current scroll position.

Here is the workaround I am using:

 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 (commonly called app.js).

This is a pure javascript solution (it is always best not to use jQuery if it's easy).

Explanation: the script checks every 200 ms if the new DOM is fully loaded, and then scrolls up and stops checking. I tried 200 ms without this loop, and sometimes it did not scroll, because the page simply did not display completely.

+9
source

You seem to understand why the problem is based on @jarrodek's comment.

As for the solution, you can either execute the @TongShen solution to pack your function in $timeout , or you can put the function call in the partial that you load.

 <!-- New partial--> <div ng-init="scrollToTop()"> </div> 

If you are viewing a change that is triggered after a click event, you can also place a function call on this element. However, it all comes down to timelines. It just depends on how everything is set up.

+1
source

Source: https://habr.com/ru/post/970148/


All Articles