How to reset scroll position on a route change?

前端 未结 2 720
半阙折子戏
半阙折子戏 2021-02-07 01:43

I spend my first couple of hours with Angular JS and I am trying to write a SPA with it. However, on changing route, the scroll position remains at its current position after ch

相关标签:
2条回答
  • 2021-02-07 01:54

    As per the ngView documentation:

    autoscroll(optional) string:

    Whether ngView should call $anchorScroll to scroll the viewport after the view is updated.

    So all you have to do is change your ng-view call to turn on autoscroll like so:

    <div ng-view autoscroll></div>
    
    0 讨论(0)
  • 2021-02-07 02:07

    After each route change there is an event fired on the $rootScope: $routeChangeSuccess. In the most basic scenario, just listen to this event and reset the scroll position to (0,0):

    $rootScope.$on("$routeChangeSuccess", function(){
         window.scrollTo(0,0);
    })
    

    In a bit more advanced case you can store, for each url, the last position before leaving the url -- then you should listen on: $routeChangeStart as well. Very primitively, the storing could be made on the $rootScope itself, but I would prefer to use JS hash object and keep it as simple angular value instead. If storing the last position should be made permanent (e.g. in localStorage), then you can consider use of angular service.

    0 讨论(0)
提交回复
热议问题