SrikanthReddy Karnati SrikanthReddy Karnati - 2 years ago 80
AngularJS Question

Infinite Scrolling doesn't seem to be working (first scroll enter data is loading)

I have a JSON data which contains 1000 products.

I am trying to show those products on my web page as a 3*3 grid using infinite scrolling.

On very first scroll only , entire data is getting loaded.

My code looks like this :

<!DOCTYPE html>
width : 200px;
height : 200px;
display : inline-block;
margin-right : 5 ;
margin-bottom : 5;
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<script src = ""></script>
<script src=""></script>
<script src = ""></script>
<script src = "ng-infinite-scroll.js"></script>

<div ng-app='myApp' ng-controller='DemoController'>
<div infinite-scroll="loadMore()" infinite-scroll-distance="0" infinite-scroll-disabled = "false">
<div ng-repeat="product in productList" class="col-md-4 panel panel-info">
<p class = "panel-heading">#{{}}&nbsp;&nbsp;{{}}</p>
<img ng-src ="{{ product.img }}" alt = "{{ product.img}}" class="imageStyle">
<h3> <small>{{}}</small></h3>
<p class="text-danger">{{product.price | currency:'&#8377;'}}</p>
<div style='clear: both;'></div>
var myApp = angular.module('myApp', ['infinite-scroll']);
myApp.controller('DemoController', function($scope,$http) {

//$scope.images =;
$scope.productList = [];
for(var i=0;i<9;i++){
$scope.loadMore = function() {
console.log('called' + $scope.productList.length);
for(var j = $scope.productList.length; j <= $scope.productList.length+9 && $scope.productList.length<1000; j++) {
console.log("j value "+j);
console.log('images array length '+$scope.productList.length);


//$scope.images = [1, 2, 3, 4, 5, 6, 7, 8];


Please suggest me changes I need to make in above code.

Working example is more appreciable.

Please help me to get this done.

Thanks in advance.

Answer Source

On very first scroll only , entire data is getting loaded.

This is due to the wrong loop termination condition:

j <= $scope.productList.length+9 && $scope.productList.length < 1000

which would cause the loop not to stop until j is less than or equal to productList.length AND productList.length is less than 1000.

Since after the initialization of the productList array, its length turns 9 and 9 is always less than 1000, you'll end up loading (pushing) all the array items in upon first call of the loadMore() function.


Instead, try something like the following (as in the docs for ngInfiniteScroll) in your loadMore() function:

var lastIndex = $scope.productList.length-1;
for (var j = 1; j <= 9; j++) { // load 9 more on every call to the loadMore function
   $scope.productList.push([lastIndex + j]);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download