Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - A simple infinite scroll

I am trying to write a similar small infinite scroll to the one found here: http://jsfiddle.net/vojtajina/U7Bz9/

I've been able to display the first 5 pieces of data, however on scroll, the further items are not being displayed.

HTML:

<div id="fixed" directive-when-scrolled="loadMore()">
  <ul>
    <li ng-repeat="i in items | limitTo: 5">{{ i.Title }}</li>
  </ul>  
</div>

JS:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.items = [
    {
       "Title":"Home"
    },
    {
       "Title":"Contact"
    },
    {
       "Title":"Help"
    },
    {
       "Title":"About"
    },
    {
       "Title":"Our Offices"
    },
    {
       "Title":"Our Locations"
    },
    {
       "Title":"Meet the Team"
    }
    ,
    {
       "Title":"Our Mission"
    },
    {
       "Title":"Join Us"
    },
    {
       "Title":"Conferences"
    },
    {
       "Title":"Tables"
    },
    {
       "Title":"Chairs"
    } 
  ];

    var counter = 0;
    $scope.loadMore = function() {
        for (var i = 0; i < 5; i++) {
            $scope.items.push({id: counter});
            counter += 10;
        }
    };

    $scope.loadMore();


});


app.directive("directiveWhenScrolled", function () {
  return function(scope, elm, attr) {
        var raw = elm[0];

        elm.bind('app', function() {
            if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                scope.$apply(attr.whenScrolled);
            }
        });
    };
});

Here's a plunker: http://plnkr.co/edit/6ggYGZx6scSoJ5PNhj67?p=preview

like image 818
Oam Psy Avatar asked Dec 06 '22 01:12

Oam Psy


1 Answers

There are two problems. First of all, what is attr.whenScrolled? Its undefined. Second one - limitTo: 5. You will allways show only 5 elements!

Here you have working code: http://plnkr.co/edit/VszvMnWCGb662azo4wAv?p=preview

What was changed? Your directive is called directiveWhenScrolled so call:

scope.$apply(attr.directiveWhenScrolled);

instead of

scope.$apply(attr.whenScrolled);

How lets deal with static limit. Change it into variable (remember about defining default value):

<li ng-repeat="i in items | limitTo: limit">{{ i.Title }}</li>

And now your loadMore function should look like this:

$scope.loadMore = function() {
    $scope.limit += 5;
};
like image 175
Kasyx Avatar answered Dec 21 '22 21:12

Kasyx