Skip to content

Instantly share code, notes, and snippets.

@SimeonC
Last active May 25, 2016 18:58
Show Gist options
  • Save SimeonC/a15055a5b9ec0c5685da to your computer and use it in GitHub Desktop.
Save SimeonC/a15055a5b9ec0c5685da to your computer and use it in GitHub Desktop.
A shim for lrInfiniteScroll to support targets. See https://github.com/lorenzofox3/lrInfiniteScroll/issues/11
appModule.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,
lastRemaining = 9999,
bindTarget = element,
calculateRemaining = function(){
return element[0].scrollHeight - (element[0].clientHeight + element[0].scrollTop);
};
if (attr.target) {
if (attr.target.toLowerCase() === 'window') {
bindTarget = angular.element(window);
element = angular.element(document.querySelector('body'))
calculateRemaining = function(){
return element[0].offsetHeight - (window.pageYOffset + window.innerHeight);
};
}
else element = angular.element(document.querySelector(attr.target));
}
lengthThreshold = parseInt(lengthThreshold, 10);
timeThreshold = parseInt(timeThreshold, 10);
if (!handler || !angular.isFunction(handler)) {
handler = angular.noop;
}
bindTarget.bind(
'scroll', function () {
var remaining = calculateRemaining();
//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;
}
);
}
};
}
]
);
@joelcdoyle
Copy link

joelcdoyle commented May 25, 2016

Adding this feature has a fairly nasty side-effect if you are using the routing features of Angular. The handler will be called multiple times due to the fact that this directive creates a new scope each time the route with your infinite scroll directive is visited. So if you navigate away and back your server call will get called that many more times. Yikes!

This is only a problem because the target is the window. Any idea how to prevent this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment