Progressive loading in ng-repeat for images, angular js

后端 未结 4 1598
萌比男神i
萌比男神i 2020-12-08 01:49

How do I implement progressive loading of content as you scroll down the page? Otherwise 1000 images would load at the same time.

相关标签:
4条回答
  • 2020-12-08 01:55

    Use infinite scrolling directive. ngInfiniteScroll

    DEMO


    HTML

    <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>
    

    JS

    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);
        }
      };
    });
    
    0 讨论(0)
  • 2020-12-08 02:01

    I've created a module that does roughly the same as ngInfiniteScroll, but does not depend on jQuery. It does take window resizing into account. ngInfiniteScroll wasn't performing properly in my application so I've build my own and it's a lot lighter.

    https://github.com/Bram77/su-endless-scroll

    0 讨论(0)
  • 2020-12-08 02:04

    Ben Nadel has a good solution for this, where he takes in account both window and document resizing. He also avoids a repaint after every ng-repeat node. Check it out.

    0 讨论(0)
  • 2020-12-08 02:13

    I didn't want to use ngInfiniteScroll the other guy posted as my mobile app does not use jQuery so there is no point in loading it just for this.

    Anyhow, I found a jsfiddle with pure Javascript that solves this problem.

    HTML

    <div id="fixed" when-scrolled="loadMore()">
        <ul>
            <li ng-repeat="i in items"></li>
        </ul>
    </div>
    

    JavaScript

    function Main($scope) {
        $scope.items = [];
        var counter = 0;
        $scope.loadMore = function() {
            for (var i = 0; i < 5; i++) {
                $scope.items.push({
                    id: counter
                });
                counter += 10;
            }
        };
        $scope.loadMore();
    }
    
    angular.module('scroll', []).directive('whenScrolled', function() {
        return function(scope, elm, attr) {
            var raw = elm[0];
            elm.bind('scroll', function() {
                if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                    scope.$apply(attr.whenScrolled);
                }
            });
        };
    });
    

    Source: http://jsfiddle.net/vojtajina/U7Bz9/

    0 讨论(0)
提交回复
热议问题