Troubleshooting problem with infinite scrolling in AngularJS with Ionic framework

I recently created a webpage with an infinite scroll page load more script using Ionic AngularJS. However, I encountered an issue where the page restarts from the beginning once it reaches the bottom.

Below is the HTML code snippet:

<ion-content class="has-header">

<ion-list>
    <ion-item ng-repeat="item in items">
      Item: {{ item.username }}
    </ion-item>

</ion-list>
<ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="10%"></ion-infinite-scroll>

</ion-content>

And here is the JavaScript code snippet:

angular.module('ionicApp', ['ionic'])
    .controller('MyCtrl', function($scope,$http) {
         $scope.noMoreItemsAvailable = false;

          $scope.loadMore = function() {

            $http.get('http://serverurl/a.php?page='+$scope.items.length).success(function(items) { 
                //$scope.username = items;
                $scope.items = items;
                //$scope.items.push(items);
                console.log(items)
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });

          };

          $scope.items = [];
    });

Please review the full code example on CodePen: http://codepen.io/gauravcoder/pen/dGZbZK?editors=101

Answer №1

It appears that your controller is only making requests for page 0 and page 10 due to a length check.

Below is a slightly revised code snippet that may work better, although I recommend implementing pagination in a more efficient manner. This code serves as a basic example:

See the Plunker link for more details - http://codepen.io/gauravcoder/pen/obovaP

angular.module('ionicApp', ['ionic']).controller('MyCtrl', function($scope,$http) {
$scope.noMoreItemsAvailable = false;
$scope.currentPage = 0;

  $scope.loadMore = function() {
    if($scope.currentPage == 3) {
       //no more items
       $scope.$broadcast('scroll.infiniteScrollComplete');
        $scope.noMoreItemsAvailable = true;
       return;
    }

    $http.get('http://serverurl/a.php?page='+$scope.currentPage).success(function(items) { 
$scope.currentPage += 1;
        //$scope.username = items;
        $scope.items = $scope.items.concat(items);
        //$scope.items.push(items);
        console.log(items)
        $scope.$broadcast('scroll.infiniteScrollComplete');
    });

  };
$scope.items = [];
});

Additionally, keep in mind that with only 3 pages available, it's advisable to include a validation for that scenario as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maintain the previous droppable positioning after refreshing the page

I am encountering an issue with the .droppable event. I have set up two sections where I can move elements, but every time the page is refreshed, the positioning of the elements reverts to the initial position. How can I maintain the last positioning of th ...

What is the technique for accessing dynamic object properties in Javascript?

I am dealing with a dynamic object where the property values change based on different data sets. For example: MyObj = { country:"Ind", Place:"Pune"} Now, I have a data value that determines which property value I need to retrieve. var MyArr = this.Filt ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

Initiating an Ajax POST request by clicking a button

I have a button on my webpage that, when clicked, currently prints the value of an element to the console using a basic function. Instead of just printing the value, I want to update my Django view by sending it through a POST request. Here's the cu ...

Are there any special CSS hacks that only work for IE8?

When it comes to Internet Explorer 8 (IE8), my preference is to utilize the following CSS: color : green; I am looking to implement a hack that exclusively impacts IE8, without affecting IE9, IE6, and 7. ...

Merge JSON objects into an array

Is there a way to merge JSON objects when the initial object is: { "total": "2" } And the second one is: [ "player1": { "score": "100", "ping": "50" }, "player2": { "score": "100", "ping": "50" ...

Retrieve geographical coordinates from image metadata using JavaScript

Seeking help with extracting the GPS Exif tag from images using NodeJS. The data is currently structured as follows: { "gps": { "GPSTimeStamp": [2147483647, 76, 41], "GPSLongitude": [76, 41, 56.622], "GPSLatitude": [30, 43, 8 ...

The value of the checkbox model in AngularJS is not defined

I'm encountering an issue where I am trying to send the value of a checkbox from my model to the server. Since the checkbox has not been interacted with on the form, Angular does not assign it a value and returns undefined when I request the value. B ...

Tips on identifying HTML email input validation using JavaScript?

Just like when you can determine whether an input element with a required attribute was successfully validated, try using the following code: if($('input[type="email"]').val() && $('input[type="email"]').val().includes('@') & ...

Is there a way to adjust the brightness of specific sections within an image using html, css, and js?

I am working on a project where I have an image with tags underneath that correspond to different parts of the image. For example, if the image is of a dog, one of the tags could be 'nose', indicating the portion of the image around the dog' ...

Guide to making a Grid element interactive using the Link component

PostsList component is responsible for rendering a list of posts. The goal is to enable users to click on a post item and be redirected to the specific post's link. const PostsListView = ({ posts, setError, isloggedin }) => { const [redirectCre ...

Guide to executing a batch file using electron

I've been struggling all morning to find a solution. I've gone through several tutorials, but I still can't wrap my head around how this should work. In my Electron app, there is a button that, when clicked, should execute a batch file (hpm ...

Guide on plotting latitude and longitude coordinates on Google Maps with Vue.js through JSON data fetched via AJAX

I have implemented a Vue.js script to fetch JSON data through an AJAX request. However, I am encountering issues with the code. <script> new Vue({ el: '#feed' , data: { details: [], }, mounted() { this.$nextTick(fu ...

How come only the final element is being displayed from an array in JavaScript, rather than all of the elements present

I am facing an issue while attempting to extract specific information from a JSON data and create a new array with key-value pairs. However, instead of getting all the elements, it only returns the last one. Here is my current code snippet: const input = ...

jQuery UI Dialog is causing my DOM elements to shift positions

I encountered an issue where my jquery ui dialog would only open once, To address this, I attempted the following solution: /* Prepare */ $('.steps > div.step-1 .bicicleta .attributos').dialog({ autoOpen:false, width: ...

Refreshing the dropdownlist data from the database without the need to reload the entire page

I am searching for a way to refresh data in a dropdown list after clicking a button. It is crucial that only the dropdown list form reloads. // Controller View public ActionResult AddRelease() { var Authors = _context.Authors.ToList(); ...

Angular $watch event does not trigger when there is a change in window.getSelection().anchorNode

My role is to monitor changes in user-selected text. I activate based on the DOM element being highlighted. Here is the function I use for this purpose: $scope.$watch(function(scope) { return window.getSelection().anchorNode }, function() { cons ...

Utilizing Vue CSS variables as inline styles

Incorporating CSS variables in my component has allowed me to dynamically set the width of a div based on computed data within the setup() setup(props) { const progressBar = PositionService.getProgressBar(props.position); const progressWidth = `${p ...

How can I properly implement a Closure or IIFE to manage an onclick event in ReactJS?

I'm encountering an issue while attempting to utilize the this object in an event handler. An undefined error related to the this object keeps popping up. My development stack includes ReactJS and Redux as well. class Chat extends Component { c ...

I encountered a ReferenceError stating that the variable "html" is not defined

Recently, I delved into the world of Node.js for the first time. During my attempt to connect my index.html file, an error message stating 'ReferenceError: html is not defined' popped up. Below is the code snippet from my index.js: var http = re ...