AngularJS upwards infinite scroll

HTML:

<style>
	.upwards-scroll-container {
		height: 300px;
		border: 1px solid black;
		overflow-y: scroll;
	}
</style>

<div data-ng-controller="UpwardsScroll">
	<div class="upwards-scroll-container" upwards-scoll="LoadMore()">
		<ul>
			<li ng-repeat="i in items">{{i.text}}</li>
		</ul>
	</div>
</div>

AngularJS controller and directive:

angular.module('myapp').controller('UpwardsScroll', function($scope, $http) {
    var counter = 1;
    var limit = 50;
	$scope.items = [];	
    $scope.LoadMore = function() {
        for (var i = 0; i < limit; i++) {
            $scope.items.unshift( { text: counter } );
            counter++;
        }
    };
    $scope.LoadMore();
});

angular.module('myapp').directive('upwardsScoll', function ($timeout) {
    return {
        link: function (scope, elem, attr, ctrl) {
            var raw = elem[0];

            elem.bind('scroll', function() {
                if(raw.scrollTop <= 0) {
                    var sh = raw.scrollHeight;
                    scope.$apply(attr.upwardsScoll);

                    $timeout(function() {
                        elem.animate({
                            scrollTop: raw.scrollHeight - sh
                        },500);
                    }, 0);
                }
            });

            //scroll to bottom
            $timeout(function() {
                scope.$apply(function () {
                    elem.scrollTop( raw.scrollHeight );
                });
            }, 0);
        }
    }
});

live preview

Advertisements