Skip to content

Instantly share code, notes, and snippets.

@BrandonDavidDee
Last active September 11, 2018 19:19
Show Gist options
  • Save BrandonDavidDee/7b8a3bfc06a45fec31a2fb91be5814d6 to your computer and use it in GitHub Desktop.
Save BrandonDavidDee/7b8a3bfc06a45fec31a2fb91be5814d6 to your computer and use it in GitHub Desktop.
Infinite Scroll with AngularJS
<!-- using Bootstrap 4 grid -->
<section ng-controller="myController">
<div class="container-fluid">
<div class="row">
<div class="col-sm-2" ng-repeat="i in images | limitTo:showThisMany">
<img ng-src="{{ i.thumbnail }}" class="img-fluid" />
</div>
</div>
<br/>
<button ng-show="showThisMany <= images.length" class="btn btn-outline-secondary btn-block" ng-click="loadMore()">
Load More
</button>
</div>
</section>
app.controller('myController',
function myController($scope, $http) {
$http.get('/api/your-resource/')
.then(function(response){
// returns an array
$scope.images = response.data;
});
// "load more" section
$scope.showThisMany = 18; // start by loading 18 images which will be 3 rows in BS4 grid
$scope.loadMore = function () {
var newValue = $scope.showThisMany + 12; // adds 2 rows of 6 images
$scope.showThisMany = newValue;
};
// below is based on this gist by Nathan Smith:
// https://gist.github.com/nathansmith/8939548
window.onscroll = function () {
var d = document.documentElement;
// document.documentElement.scrollTop would not work in Safari
// so I use window.scrollY in its place
var offset = window.scrollY + window.innerHeight;
var height = d.offsetHeight;
if (angular.isDefined($scope.images)) {
// once images resource returns its promise / is defined we can use its length
if (offset === height && $scope.showThisMany <= $scope.images.length) {
// end --------- of --------- page
$scope.$apply(function () {
$scope.loadMore();
})
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment