Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material autocomplete infinite scroll with $http request

Does autocomplete support infinite scroll from a remote source? The scenario is like this. The user types few letters, the autocomplete filters out the result. Still the result is too huge to fit in the result area. The user wants to scroll the "returned result". I find this scenario very straight forward, however, I found nothing online.

Please advise.

like image 965
Jalal El-Shaer Avatar asked Dec 01 '16 13:12

Jalal El-Shaer


1 Answers

I guess we need go with custom directive for your requirement.

I have created directive which actually binds scroll event on "md-virtual-repeat-container" which holds the items list after rendering.

JS

Your directive will be like below. Purpose of this directive is get scroll event and call attached function when user reach at the end of scroll. Condition "new Date().getTime() - now > 100" will acts as a throttle API call. You can change throttle time from 100 milli sec to any ms if you want to limit your API calls between 100 milli sec of user action.

.directive('lazyLoadData', function($compile) {
     return {
         link: function(scope, el, attrs) {
            var now = new Date().getTime();
            var rep = angular.element(document.getElementsByClassName("md-virtual-repeat-scroller"));
            rep.on('scroll', function(evt){
               if (rep[0].scrollTop + rep[0].offsetHeight >= rep[0].scrollHeight)
                  if (new Date().getTime() - now > 1000) {                  
                     now = new Date().getTime();
                     scope.$apply(function() { 
                        scope.$eval(attrs.lazyLoadData); 
                     });
                  }                  
            });
         }
    }; 
});

HTML Your html will like as below,

<md-autocomplete flex
                 md-selected-item="ctrl.selectedItem"
                 md-search-text="searchText"
                 md-items="item in querySearch(searchText)"
                 md-item-text="item.login"
                 md-delay="300"
                 md-floating-label="Search Github Users"
                 lazy-load-data="querySearch()" <!--New directive will go here -->
>
   <div layout="row" class="item" layout-align="start center">
      <img ng-src="{{item.avatar_url}}" class="avatar" />
      &nbsp;&nbsp;
      <span md-highlight-text="searchText">{{item.login}}</span>  
   </div>
</md-autocomplete>

Here is DEMO

*Please note currently i am appending same data to my records array because i dont have actual API. But you can extend your API to get paged records based on searched text. Refer https://github.com/davidchin/angular-endless-scroll OR http://www.dotnetawesome.com/2016/03/infinite-scroll-for-facebook-like-pagination-angularjs.html

like image 99
user3249448 Avatar answered Sep 28 '22 20:09

user3249448