How to reset scroll position on a route change?

感情迁移 提交于 2019-12-03 04:40:26
Matt Way

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>

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!