簡體   English   中英

使用AngularJS中的ngInfiniteScroll指令實現反向無限滾動

[英]Implementing a reverse infinite scroll using ngInfiniteScroll directive in AngularJS

我想從這里使用ngInfiniteScroll指令: httpngInfiniteScroll在我的angular js應用程序中實現反向無限滾動(就像在聊天小部件中一樣)。 但是,該指令的文檔似乎沒有提到如何實現。 它僅記錄了如何實現標准無限滾動。 有人可以在這方面指導我嗎? 謝謝!

PS:我熱衷於使用這個指令,因為它處理DOM控件; 來自angular的標准無限滾動指令在滾動時不斷創建DOM元素,永遠不會刪除。

我認為您應該選擇基於模型的方法(特別適合角度),即當您向上滾動並達到限制時,您可以加載更多數據並將其插入到消息集合的開頭(您也可以刪除最新的數據)你想限制因性能原因而加載的html節點數量。

這是我和lrInfiniteScroll一起使用的方法

根本沒有dom操作,它只是檢測你向下滾動到達底部(帶有去抖動)並觸發你綁定的處理程序,這樣你就可以做任何你想做的事情,特別是改變你的模型:你的應用程序仍然是模型驅動的

我已經改變了邏輯以使滾動向上行為,但這個想法保持不變

(function (ng) {
'use strict';
var module = ng.module('lrInfiniteScroll', []);

module.directive('lrInfiniteScroll', ['$timeout', function (timeout) {
    return{
        link: function (scope, element, attr) {
            var
                lengthThreshold = attr.scrollThreshold || 50,
                timeThreshold = attr.timeThreshold || 400,
                handler = scope.$eval(attr.lrInfiniteScroll),
                promise = null,
                lastScrolled = -9999;

            lengthThreshold = parseInt(lengthThreshold, 10);
            timeThreshold = parseInt(timeThreshold, 10);

            if (!handler || !ng.isFunction(handler)) {
                handler = ng.noop;
            }

            element.bind('scroll', function () {

                var scrolled = element[0].scrollTop;
                //if we have reached the threshold and we scroll up
                if (scrolled < lengthThreshold && (scrolled - lastScrolled) < 0) {
                    //if there is already a timer running which has no expired yet we have to cancel it and restart the timer
                    if (promise !== null) {
                        timeout.cancel(promise);
                    }
                    promise = timeout(function () {
                        handler();
                        //scroll a bit againg
                        element[0].scrollTop=element[0].clientHeight/2;
                        promise = null;
                    }, timeThreshold);
                }
                lastScrolled = scrolled;
            });


            //scroll first to the bottom (with a delay so the elements are rendered)
            timeout(function(){
                element[0].scrollTop=element[0].clientHeight;
            },0);
        }

    };
}]);
})(angular);

一個運行的例子

你可以在github上使用這個zInfiniteScroll項目 ,它會讓你向下滾動結束或向上滾動到頂部以獲取更新供稿。

如果要在收到消息時添加自動向下滾動,請綁定此ngSmoothScroll項目

這是用例:

<body ng-app="myApp" ng-controller="mainCtrl">
    <div z-infinite-scroll="loadOlder" inverse="false" body-scroll="true">
        <div smooth-scroll scroll-if="{{$last}}" duration="0" ng-repeat="obj in messages">
{{obj.message}}
        </div>
    </div>
</body>

這是來自plunker的演示

它將收到消息10秒,如果您滾動到頂部,將加載歷史記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM