Retain scroll position on route change in AngularJS?

created a directive that works on the window scroll ( it could updated to work on any element though ) html usage

where "service.scrollY" MUST be a variable within a service. Services retain their state and values, controllers are recreated every time they load and clear their values so you cant use them to store persistent data. the controller has a scope variable pointing to the service. directive js
app.directive('ngKeepScroll', function ($timeout) { return function (scope, element, attrs) { //load scroll position after everything has rendered $timeout(function () { var scrollY = parseInt(scope.$eval(attrs.ngKeepScroll)); $(window).scrollTop(scrollY ? scrollY : 0); }, 0); //save scroll position on change scope.$on("$routeChangeStart", function () { scope.$eval(attrs.ngKeepScroll + " = " + $(window).scrollTop()); }); } });

0 comments: