angular-ui / ui-scroll

Unlimited bidirectional scrolling over a limited element buffer for AngularJS applications
http://angular-ui.github.io/ui-scroll/demo/
MIT License
327 stars 107 forks source link

Get DOM element at index #234

Closed forresthopkinsa closed 5 years ago

forresthopkinsa commented 5 years ago

Is there any way to get the DOM element at a certain ui-scroll index? Similar to topVisibleElement, but for any arbitrary index.

dhilt commented 5 years ago

@forresthopkinsa There is no API for direct access to DOM elements. But I can suggest 2 approaches to solve this issue. First one is about accessing via special attribute:

    <div ui-scroll="item in datasource" data-sid="item.index">{{item.text}}</div>

and then plain old

viewportElement.querySelector(`[data-sid="${index}"]`)

You see, it will not allow you to deal with index set by the ui-scroll, but with index set by the app externally.

Another approach might help with native index, it implies Adapter applyUpdates method using, because the third argument of applyUpdates in "updater" signature is html element bound with iterated item:

        $scope.adapter.applyUpdates((item, scope, element) => {
          if(myItemIndexInt === scope.$index) { // internal index set by the ui-scroll
            element[0].innerHTML += "*";
          }
         // OR
          if(myItemIndexExt === item.index) { // external index set by the app
            element[0].innerHTML += "*";
          }
        });

I published small demo on stackblits: https://stackblitz.com/edit/angular-ui-scroll-v1-7-6-access-to-dom-elements?file=index.html showing the second case. Hope this helps!

dhilt commented 5 years ago

@forresthopkinsa I just realized that the first approach can do it with internal indexes:

<div ui-scroll="item in datasource" data-index="{{$index}}">{{item.text}}</div>

Here $index is an internal scope index set by the ui-scroll. Then proceed with

viewportElement.querySelector(`[data-index="${myItemIndexInt}"]`)
forresthopkinsa commented 5 years ago

Excellent answer, totally solves my problem. Thanks!