AngularJS: Infinite Scrolling

by Nivaldo

HTML

<script src="http://code.angularjs.org/1.0.0rc9/angular-1.0.0rc9.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="fixed" when-scrolled="loadMore()">
  <ul>
    <li ng-repeat="item in items">{{item.id}}</li>
  </ul>  
</div>

CSS

li {
  height: 120px;
  border-bottom: 1px solid gray;
}

#fixed {
    height: 400px;
    overflow: auto;
}

JavaScript

function Main($scope) {
    $scope.items = [];
    var numberOfRows = 5;
    
    $scope.loadMore = function() {
        last = $scope.items.length == 0 ? 1 : $scope.items.length + 1;
        $.ajax({
            type: "GET",
            url: "http://mllab1.apa.org:8020/apps/author-aggreg/responders/au-aggreg-rows-rsp.xqy",
            data: {rowStart:last,rowCount:numberOfRows},
            success: function(data){
              for (var i = 0; i < numberOfRows; i++) {
                    $scope.items.push({id: data.children[i].property.substring(3) + ' (' + data.children[i].value + ')'});
                }
              $scope.$apply(); //very important so that results from Ajax call notifies Angular
            }
        });
    };
    
    $scope.loadMore();
}

angular.module('scroll', []).directive('whenScrolled', function() {
    return function(scope, elm, attr) {
        var raw = elm[0];
        
        elm.bind('scroll', function() {
            if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                scope.$apply(attr.whenScrolled);
            }
        });
    };
});