Retain scroll position on route change in AngularJS?

后端 未结 15 1461
太阳男子
太阳男子 2020-11-30 19:49

Sample app: http://angular.github.com/angular-phonecat/step-11/app/#/phones

If you choose the last phone \"Motorola charm\" it will show you the details of the phone

15条回答
  •  半阙折子戏
    2020-11-30 20:29

    I have used the solution of @Joseph Oster in order to create a directive. I have also taken the liberty to update the answer to use:

    • $locationChangeStart
    • $locationChangeSuccess

    as the other events are obsolete.

    Fiddle is here: http://jsfiddle.net/empie/p5pn3rvL/

    Directive source:

    angular.module('myapp', ['ngRoute'])
        .directive('autoScroll', function ($document, $timeout, $location) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                scope.okSaveScroll = true;
    
                scope.scrollPos = {};
    
                $document.bind('scroll', function () {
                    if (scope.okSaveScroll) {
                        scope.scrollPos[$location.path()] = $(window).scrollTop();
                    }
                });
    
                scope.scrollClear = function (path) {
                    scope.scrollPos[path] = 0;
                };
    
                scope.$on('$locationChangeSuccess', function (route) {
                    $timeout(function () {
                        $(window).scrollTop(scope.scrollPos[$location.path()] ? scope.scrollPos[$location.path()] : 0);
                        scope.okSaveScroll = true;
                    }, 0);
                });
    
                scope.$on('$locationChangeStart', function (event) {
                    scope.okSaveScroll = false;
                });
            }
        };
    })
    

提交回复
热议问题