How to retain scroll position of ng-repeat in AngularJS?

前端 未结 9 1440
梦谈多话
梦谈多话 2020-12-05 00:47

DEMO

List of objects is rendered using ng-repeat. Suppose that this list is very long and user is scrolling to the bottom to see some objects.

W

9条回答
  •  情歌与酒
    2020-12-05 01:04

    Below is an improvement to Arthur's version that prevents scrolling regardless if the added item is added above or below the scroll: JS Bin

    angular.module("Demo", [])
    
    .controller("DemoCtrl", function($scope) {
      $scope.items = [];
      
      for (var i = 0; i < 10; i++) {
        $scope.items[i] = {
          id: i,
          name: 'item ' + i
        };
      }
      
      $scope.addNewItemTop = function() {
        $scope.items.unshift({
          id: $scope.items.length,
          name: "item " + $scope.items.length
        });
      };
      
      $scope.addNewItemMiddle = function() {
        $scope.items.splice(5, 0, {
          id: $scope.items.length,
          name: "item " + $scope.items.length
        });
      };
      
      $scope.addNewItemBottom = function() {
        $scope.items = $scope.items.concat({
          id: $scope.items.length,
          name: "item " + $scope.items.length
        });
      };
    })
    
    .directive("keepScroll", function(){
      
      return {
    
        controller : function($scope){
          var element = 0;
          
          this.setElement = function(el){
            element = el;
          };
    
          this.addItem = function(item){
            console.group("Item");
            console.log("OffsetTop: " + item.offsetTop);
            console.log("ScrollTop: " + element.scrollTop);
            
            if(item.offsetTop <= element.scrollTop) {
              console.log("Adjusting scorlltop position");
              element.scrollTop = (element.scrollTop+item.clientHeight+1); //1px for margin
            } else {
              console.log("Not adjusting scroll");
            }
            console.groupEnd("Item");
          };
          
        },
        
        link : function(scope,el,attr, ctrl) {
          
         ctrl.setElement(el[0]);
          
        }
        
      };
      
    })
    
    .directive("scrollItem", function(){
      
      
      return{
        require : "^keepScroll",
        link : function(scope, el, att, scrCtrl){
          scrCtrl.addItem(el[0]);
        }
      };
    });
    .wrapper {
      width: 200px;
      height: 300px;
      border: 1px solid black;
      overflow: auto;
      /* Required for correct offsetParent */
      position: relative; 
    }
    .item {
      background-color: #ccc;
      height: 100px;
      margin-bottom: 1px;
    }
    
    
    
    
      
      JS Bin
    
    
      
    {{ item.name }}

提交回复
热议问题