1

I reloaded the route using $route.reload() and I need to retain the same scroll position before reloads the page.

But, after reloading the route then the scroll position points at the top.

For Instance, if I'm reloading my application using,

$window.location.path();

It retains the same scroll position. But I don't want to reload the application. I just want to reload the route only and need to keeps the same scroll position.

Please give your valuable commands.

Thanks in advance.

d-_-b
  • 21,536
  • 40
  • 150
  • 256
Dinesh ML
  • 921
  • 11
  • 15
  • could use `$scope.on('$destroy')` to store current `scrollTop` in a service and when controller loads again see if that service variable is set. A simple directive would likely be best – charlietfl Dec 20 '14 at 06:31

2 Answers2

0

I have sample code posted here AngularJsScrollPersisterDemo

The code works for me when I host the files in a website. The magic is really done in the directive and the service.

directive:

(function (angular) {
    "use strict";

    angular.module("ScrollPersisterApp").directive("scrollPersister", ["scrollPersisterService", scrollPersister]);

    function scrollPersister(scrollPersisterService) {
        return {
            restrict: "A",
            link: function (scope, element, attributes) {
                element[0].scrollTop = scrollPersisterService.GetScrollTop();

                scope.$on('$destroy', function () {
                    scrollPersisterService.SetScrollTop(element[0].scrollTop);
                });
            }
        };
    }
})(angular);

The directive sets the scrollTop of the div via the injected scrollPersisterService when it is destroyed, such as by a $route.reload(). Upon reload, the directive reads the scrollTop value from the scrollPersisterService and sets it as the scrollTop of the div via JavaScript.

See my github repository I linked for the full example. I have tested this code in the latest version of Chrome and it works great.

David Gunderson
  • 671
  • 14
  • 20
0

You can set a custom state param that would tell your controller where to scroll the page to.

angular.module("app").controller('MyController', function($scope, $state, $stateParams, $timeout) {
   if($stateParams.scrollY) {
     $timeout(function() {
        window.scrollTo(0, $stateParams.scrollY);
     });
   }
   $scope.reloadRoute = function(){
     params = angular.copy($stateParams);
     params.scrollY = window.scrollY;
     $state.transitionTo($state.current, params, {
       reload: true,
       inherit: false,
       notify: true
     });
   }
});

Inspired by this answer.

Community
  • 1
  • 1
fracz
  • 20,536
  • 18
  • 103
  • 149