在ng-repeat中逐行加载图像,角度为js

The*_*yYo 20 lazy-loading progressive angularjs angularjs-ng-repeat

当您向下滚动页面时,如何实现渐进式内容加载?否则将同时加载1000张图像.

Epo*_*okK 24

使用无限滚动指令.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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

  • 默认情况下,AngularJS**不使用jQuery.而zepto绝对是一个糟糕的选择(https://github.com/angular/angular.js/pull/3350) (7认同)

The*_*yYo 17

我不想使用ngInfiniteScroll其他人发布,因为我的移动应用程序不使用jQuery所以没有必要加载它只是为了这个.

无论如何,我发现了一个用纯Javascript解决这个问题的jsfiddle.

HTML

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

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);
            }
        });
    };
});
Run Code Online (Sandbox Code Playgroud)

资料来源:http://jsfiddle.net/vojtajina/U7Bz9/

  • 此解决方案不处理页面调整大小(由用户)或div调整大小,因此即使有更多项目"等待"添加,您也可能留有空白. (2认同)
  • 这也使用了Angular,就像EpokK给出的无限滚动答案一样. (2认同)