gpt4 book ai didi

javascript - Angular Directive(指令)中的无限滚动

转载 作者:行者123 更新时间:2023-11-28 00:23:56 24 4
gpt4 key购买 nike

我编写了以下无限滚动指令,我的问题是我无法弄清楚为什么它在加载指令时只触发一次,我需要您关于如何使我的列表无限滚动的建议。

我用它来远程获取数据,每次调用它时我都会添加到计数器 25,因此每次它都会返回更多数据。

谢谢,

angular.module('MyApp')
.controller('InboxCtrl', function($scope, InboxFactory) {

var counter = 0;

$scope.loadData = function() {
var promise = InboxFactory.getEvents(counter);
promise.then(function(result) {
$scope.events = result;
});
counter += 25;
};

});

angular.module('MyApp')
.factory('InboxFactory', function($http, $q) {
// Service logic

var defered = $q.defer();

function getUrl(count) {
return "api/inbox/get?request={'what':'Search','criteria':'inbox','criteriaId':null,'startTime':null,'endTime':null,'offset':" + count + ",'limit':25,'order':'event_time','direction':'DESC','source':''}";
}

function extract(result) {
return result.data.data;
}

// Public API here
return {
getEvents: function(count) {
$http.get(getUrl(count)).then(
function(result) {
defered.resolve(extract(result))
}, function(err) {
defered.reject(err);
}
);

return defered.promise;
}
};
});

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

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

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

element.bind('scroll', function() {
var
remaining = element[0].scrollHeight - (element[0].clientHeight + element[0].scrollTop);

//if we have reached the threshold and we scroll down
if (remaining < lengthThreshold && (remaining - lastRemaining) < 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();
promise = null;
}, timeThreshold);
}
lastRemaining = remaining;
});
}

};
}
]);
<ul class="inbox-list" infinite-scroll="loadData()">
<li class="clearfix" ng-repeat="event in events">{{event}}</li>
</ul>

最佳答案

我做了一些更改,更重要的是使用 ng-transclude 并为指令创建一个新的作用域来传递方法和参数。您可以看看jsbind 。当然,数据是硬编码的,所以我可以伪造这种行为。

<ul class="inbox-list" my-infinite-scroll composite-method="loadData()">

关于javascript - Angular Directive(指令)中的无限滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29741112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com