How to reset scroll position on a route change?
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.