AngularJS - 一个简单的无限滚动 [英] AngularJS - A simple infinite scroll

查看:299
本文介绍了AngularJS - 一个简单的无限滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个类似小无限滚动到一个在这里找到: http://jsfiddle.net / vojtajina / U7Bz9 /

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

我已经能够显示前5个数据,但是在滚动,不被显示进一步的项目。

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);
            }
        });
    };
});

下面是一个plunker: http://plnkr.co/edit/6ggYGZx6scSoJ5PNhj67?p = preVIEW

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

推荐答案

有两个问题。首先,什么是 attr.whenScrolled ?它的定义。第二个 - limitTo:5 。你会永诺只显示5个元素!

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

在这里,你有工作code: http://plnkr.co/编辑/ VszvMnWCGb662azo4wAv?p = preVIEW

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

什么改变?您的指令被称为 directiveWhenScrolled 这样的呼叫:

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

scope.$apply(attr.directiveWhenScrolled);

而不是

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>

现在你的 loadMore 函数应该是这样的:

$scope.loadMore = function() {
    $scope.limit += 5;
};

这篇关于AngularJS - 一个简单的无限滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆