How to retain scroll position of ng-repeat in Angu

2019-01-13 13:10发布

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

9条回答
一夜七次
2楼-- · 2019-01-13 13:58

There are, I believe, only a few possible solutions

1) Don't add the item (as per the other answer)

2) Add the item at bottom, so the list doesn't move.

3) Add the item at top and scroll the screen automatically so that the new item's height is accounted for, and everything is kept seemingly as before. The list will move down, but the viewable screen itself will also move - so relatively nothing will be seen to move. Well other elements that are not part of list will, but that might actually look quite nice...

查看更多
做个烂人
3楼-- · 2019-01-13 13:59

You know other people are trying to solve this problem using a different approach in terms of UI. They don't just POP new items on top, but instead they show a small clickable link on top stating how many new items are added since he last checked it.

[2 new items, Click here to refresh]

item 5
item 4
item 3

Check out how twitter is solving this. **[Let me attach a screenshot for you shortly.]**

I know it's a bit contradicting with want you want, but perhaps this is better in terms of UX? User wants to know if there are new items coming in.

查看更多
看我几分像从前
4楼-- · 2019-01-13 14:01

You need to add a scrollspy directive to your container that updates its position on every user scroll, and gets notified on every repeat render so it can reposition it self to its saved state. your html might look like this

<div scrollspy id="myscrollspy">
     <ul>
       <li ng-repeat="" notifyscroll></li>
     </ul>
</div>

the scroll spy would have the required css overflow settings and scroll-x or scroll-y to keep track of the current scroll and avoid polluting the scope it should also watch for an event comming from the ng-repeat that tells him a change occured and should set the scrool.

ng-repeat could notify by attaching a new directive notify scroll that launches an event. not sure if curretn version of angular supports postrender event.

the way to position the scroll will depend on whether you are using a 3rd party library $.scrollTop(pos) or no. this will do it or should. hope it helps

查看更多
登录 后发表回答