3

I am trying to recreate a simple example of ngInfiniteScroll provided on their demo page. The loadMore() function never triggers and I do not know why.

Here's the code: http://jsfiddle.net/uVxb8/3/.

<div ng-app='myApp' ng-controller='DemoController'>
  <div infinite-scroll='loadMore()'  infinite-scroll-distance='2'>
    <img ng-repeat='image in images' ng-src='http://placehold.it/225x250&text={{image}}'>
  </div>
</div>

var myApp = angular.module('myApp', ['infinite-scroll']);

myApp.controller('DemoController', function($scope) {
  $scope.images = [1, 2, 3, 4, 5, 6, 7, 8];

  $scope.loadMore = function() {
    var last = $scope.images[$scope.images.length - 1];
    for(var i = 1; i <= 8; i++) {
      $scope.images.push(last + i);
    }
  };
});

1 Answers1

1

Your method looks very complicated. Here is what I wrote (and took from another question here I believe) in the directive, to do I believe the exact same behaviour (when scrolled down, it triggers a function that loads more of the same content):

RandomName.directive('isScrolled', ['$window', '$document', function($window, $document) {
    return {

        link: function($scope, elem, attr) {
                var $myWindow = angular.element($window);
                var $myDoc = angular.element($document);

                $myWindow.bind('scroll', function() {
                    if ($myWindow.height() + $myWindow.scrollTop() >= $myDoc.height()) {
                        $scope.$apply(attr.isScrolled);
                    }
                });
            }
    }
}]);

I "listen" to the scroll event, and then everytime it happens I check if it's at the end of the page, if it is I trigger my function through the attribute. In this specific case, it triggers it only when your scroll to the very end, you probably can do something smoother.

Mimu
  • 373
  • 2
  • 3
  • 13
  • The method is copied and pasted from ngInfiniteScroll (http://binarymuse.github.io/ngInfiniteScroll/). I added your directive and tested it but it is not working. http://jsfiddle.net/uVxb8/7/. – George Richardson Jul 07 '14 at 15:39
  • You need to change what's inside the if with this: `elem[0].scrollTop + elem[0].offsetHeight >= elem[0].scrollHeight`, see this fiddle from where I took my solution: http://jsfiddle.net/vojtajina/U7Bz9/. I changed it to listen to the browser scrolling instead of the element scrolling (like in fiddle). – Mimu Jul 07 '14 at 16:16