Retain scroll position on route change in AngularJS?

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

    For those of you that went with emp's answer, but were using angular ui-router >= version 1.0.0 (current 1.0.3), please see his directive rewritten, using ui-routers new transitions.

    HTML

    Angular Directive

    angular.module("app")
        .directive("keepScrollPos", function($transitions, $state, $window, $timeout, $location, $anchorScroll) {
    
            // cache scroll position of each state's templateUrl
            var scrollPosCache = {};
    
            return {
                link: function(scope, element, attrs) {
    
    
                    $transitions.onStart({ }, function( trans ) {
    
                        // store scroll position for the current view
                        if (trans.from().name) {
                            scrollPosCache[trans.from().templateUrl] = [ $window.pageXOffset, $window.pageYOffset ];
                        }
    
                        trans.promise.finally(function () {
    
    
                            // if hash is specified explicitly, it trumps previously stored scroll position
                            if ($location.hash()) {
                                $anchorScroll();
    
                            // else get previous scroll position; if none, scroll to the top of the page
                            } else {
                                var prevScrollPos = scrollPosCache[trans.to().templateUrl] || [ 0, 0 ];
                                $timeout(function() {
                                    $window.scrollTo(prevScrollPos[0], prevScrollPos[1]);
                                }, 200);
                            }
                        });
                    });
                }
            }
        });
    

提交回复
热议问题