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

前端 未结 9 1428
梦谈多话
梦谈多话 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:22

    It maybe solved quite elegantly, by using scrollTop property of div. I used two directives - one handles scroll position of the wrapper element, the other register new elements. Give me a shout if anything unclear.

    DEMO

    JS:

    .directive("keepScroll", function(){
    
      return {
    
        controller : function($scope){
          var element = null;
    
          this.setElement = function(el){
            element = el;
          }
    
          this.addItem = function(item){
            console.log("Adding item", item, item.clientHeight);
            element.scrollTop = (element.scrollTop+item.clientHeight+1);
           //1px for margin from your css (surely it would be possible
           // to make it more generic, rather then hard-coding the value)
          };
    
        },
    
        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]);
        }
      }
    })
    

    HTML:

    {{ item.name }}

提交回复
热议问题