angular.module('fr.infiniteScrollCtrl', []) .service('infiniteScrollCtrl', ['$window', '$http', '$compile', function ($window, $http, $compile) { return function (scope, element) { try { scope.currentPage = parseInt($window.location.href.match(/\/page\/(\d+)/)[1], 10); } catch (e) { scope.currentPage = 1; } scope.loadMoreEnabled = true; scope.infiniteScrollDisabled = true; scope.pagesScrolled = 0; scope.enableInfiniteScroll = function () { scope.infiniteScrollDisabled = false; }; scope.infiniteScroll = function () { // Disable infinite scroll until we load the next page. scope.infiniteScrollDisabled = true; // Let others know that posts are loading. scope.postsLoading = true; scope.infiniteScrollError = null; // Load the page. $http.get(DataStore.postsEndpointUrl + '?page=' + (scope.currentPage + 1) + ((DataStore.currentStage) ? '&stageTree=' + DataStore.currentStage.tree : '') + ((DataStore.legendary) ? '&legendary=1' : '') + ((DataStore.search) ? '&q=' + encodeURIComponent(DataStore.search) : '') ) .then(function (response) { // Increment current page. scope.currentPage++; // Increment number of pages scrolled. scope.pagesScrolled++; // Append the newly loaded content. element.append($compile(response.data)(scope)); // If we did not scroll more than 15 pages. if (scope.pagesScrolled < 15) { // Re-enabled infinite scroll scope.infiniteScrollDisabled = false; // Disable "Load more" button. Assumes that the button is no longer needed because infinite scroll is now enabled. scope.loadMoreEnabled = false; } // If we scrolled more than 15 pages. else { // Re-enable "Load more" button. scope.loadMoreEnabled = true; // Reset pages scrolled count. scope.pagesScrolled = 0; } // Let everyone know that posts finished loading. scope.postsLoading = false; // Track the page view in Google analytics. ga('send', 'event', 'InfiniteScroll', 'Loaded', $window.location.href, scope.currentPage); // history.replaceState({}, '', '/page/' + scope.currentPage); }) .catch(function (response) { scope.postsLoading = false; if (response.status === 404) { scope.loadMoreEnabled = false; } if (response.status === 429) { // eslint-disable-next-line prefer-destructuring scope.infiniteScrollError = response.data.errors[0]; } }); }; }; }]);