Retain scroll position on route change in AngularJS?

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

    I made a version that works with any overflowed element, not just the document body:

    .directive("keepScrollPos", function($route, $timeout, $location, $anchorScroll) {
    
      // cache scroll position of each route's templateUrl
      var cache = {};
    
      return {
        restrict : 'A',
        link: function($scope, elements, attrs){
    
          $scope.$on('$routeChangeStart', function() {
    
            // store scroll position for the current view
            if($route.current)
              cache[$route.current.loadedTemplateUrl + ':' + attrs.keepScrollPos] = [elements[0].scrollLeft, elements[0].scrollTop];              
    
          });
    
          $scope.$on('$routeChangeSuccess', function(){
            // if hash is specified explicitly, it trumps previously stored scroll position
            if($location.hash()){
              $anchorScroll();
              return;
            }
    
            // else get previous scroll position and apply it if it exists
            var pos = cache[$route.current.loadedTemplateUrl + ':' + attrs.keepScrollPos];
            if(!pos)
              return;
    
            $timeout(function(){                  
              elements[0].scrollLeft = pos[0];
              elements[0].scrollTop = pos[1];            
            }, 0);
    
          });
    
        }
      }
    
    })
    

    Use it like:

    ...

提交回复
热议问题