How to reset scroll position on a route change?

前端 未结 2 717
半阙折子戏
半阙折子戏 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 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.

提交回复
热议问题