forked from lorenzofox3/lrInfiniteScroll
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lrInfiniteScroll.js
70 lines (61 loc) · 3.03 KB
/
lrInfiniteScroll.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
(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,
handlerTop = scope.$eval(attr.lrInfiniteScroll),
handlerBottom = scope.$eval(attr.lrInfiniteScrollInverse),
inverse = (typeof handlerBottom == 'function') ? true : false,
promise = null,
lastRemaining = 9999,
lastRemainingInverse = 9999;
lengthThreshold = parseInt(lengthThreshold, 10);
timeThreshold = parseInt(timeThreshold, 10);
if (!handlerTop || !ng.isFunction(handlerTop)) {
handlerTop = ng.noop;
}
if (!handlerBottom || !ng.isFunction(handlerBottom)) {
handlerBottom = ng.noop;
}
element.bind('scroll', function () {
var el = element[0];
var remainingInverse = inverse ? el.scrollTop : null;
var remaining = el.scrollHeight - (el.clientHeight + el.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 () {
if (typeof handlerTop == 'function') {
handlerTop();
}
promise = null;
}, timeThreshold);
}
lastRemaining = remaining;
if (remainingInverse !== null && remainingInverse < lengthThreshold && (remainingInverse - lastRemainingInverse) < 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 () {
if (typeof handlerBottom == 'function') {
handlerBottom();
}
promise = null;
}, timeThreshold);
}
lastRemainingInverse = remainingInverse;
});
element.on('$destroy', function() {
$timeout.cancel(promise);
});
}
};
}]);
})(angular);