What is the right way to load data (json) with angular when scrolling down?
3 Answers
HTML
<div id="fixed" when-scrolled="loadMore()">
<ul>
<li ng-repeat="i in items">{{product.name}}</li>
</ul>
</div>
JS
app.controller("MainController", function($scope, $http){
var counter = 0;
$scope.products = [];
$scope.loadMore = function() {
for (var i = 0; i < 10; i++) {
$scope.products.push({name: counter});
counter += 10;
}
};
$scope.loadMore();
}]);
myApp.directive("whenScrolled", function(){
return{
restrict: 'A',
link: function(scope, elem, attrs){
// we get a list of elements of size 1 and need the first element
raw = elem[0];
// we load more elements when scrolled past a limit
elem.bind("scroll", function(){
if(raw.scrollTop+raw.offsetHeight+5 >= raw.scrollHeight){
scope.loading = true;
// we can give any function which loads more elements into the list
scope.$apply(attrs.whenScrolled);
}
});
}
}
});
Working Example:http://plnkr.co/edit/FBaxdekW1Ya04S7jfz0V?p=preview?
1 Comment
What we did is make a directive that binds to the scroll event of the window and calls a scope function to load the data.
Or you could use ngInfiniteScroll.
1 Comment
Virtual Scroll: Display only a small subset of the data that is in the viewport and keep changing the records as the user scrolls. It keeps the number of DOM elements constant hence boosting the performance of the application.
this article so helpful
https://medium.com/codetobe/learn-how-to-us-virtual-scrolling-in-angular-7-51158dcacbd4