Retain scroll position on route change in AngularJS?

后端 未结 15 1462
太阳男子
太阳男子 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:27

    i 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());
            });
        }
    });
    

提交回复
热议问题