如何在 AngularJS 中保留 ng-repeat 的滚动位置? [英] How to retain scroll position of ng-repeat in AngularJS?

查看:26
本文介绍了如何在 AngularJS 中保留 ng-repeat 的滚动位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

演示

对象列表使用 ng-repeat 呈现.假设这个列表很长并且用户滚动到底部以查看一些对象.

当用户观察一个对象时,一个新项目被添加到列表的顶部.这会导致观察对象改变其位置,即用户突然在观察对象的同一位置看到其他东西.

当添加新项目时,您将如何将观察到的对象保持在同一位置?

这里的游乐场

解决方案

通过使用 divscrollTop 属性,它可能会非常优雅地解决.我使用了两个指令 - 一个处理包装元素的滚动位置,另一个注册新元素.如果有什么不清楚的地方,请告诉我.

演示

JS:

.directive("keepScroll", function(){返回 {控制器:功能($范围){var 元素 = null;this.setElement = function(el){元素 = el;}this.addItem = function(item){console.log("添加项目", item, item.clientHeight);element.scrollTop = (element.scrollTop+item.clientHeight+1);//1px 从你的 css 中获取边距(当然有可能//使其更通用,而不是对值进行硬编码)};},链接:函数(范围,el,attr,ctrl){ctrl.setElement(el[0]);}};}).directive("scrollItem", function(){返回{要求:^keepScroll",链接:函数(范围,el,att,scrCtrl){scrCtrl.addItem(el[0]);}}})

HTML:

<div class="item" scroll-item ng-repeat="item in items | orderBy: '-id'">{{ 项目名称 }}

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.

While user is observing an object, a new item is added to the top of the list. This causes the observed object to change its position, i.e. the user suddenly sees something else at the same place of the observed object.

How would you go about keeping the observed object at the same place when new items are added?

PLAYGROUND HERE

解决方案

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:

<div class="wrapper" keep-scroll>
  <div class="item" scroll-item ng-repeat="item in items  | orderBy: '-id'">
    {{ item.name }}
   </div>
</div>

这篇关于如何在 AngularJS 中保留 ng-repeat 的滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆