Fetch a list of 10 items at a time using AngularJS with Ionic framework's infinite scroll feature

I'm currently working on incorporating an ion-infinite-scroll feature using the ionic framework. My REST API allows me to set the index in order to request a specific range of data. Here's what my Service looks like, with 'begin' and 'end' representing the indexes:

this.GetUserRatings = function (id, begin, end) {
            return $http.get($rootScope.endPoint + '/user/' + id + '/ratings/'+ begin + '/' + end);
        };  

Upon initial page reload, I want to display 10 items in the list. Therefore, in my controller it would look something like this:

 UserService.GetUserRatings($stateParams.id, 1, 10)
        .success(function (data) {
          $scope.userRatings = angular.fromJson(data);
          }).error(function(error) {
                    //handle error
        });

As I continue scrolling down the list, I aim for the ion-infinite-scroll component to fetch the next 10 items (11 - 20), then the following batch (21 - 30), and so forth. How can I achieve this?

$scope.loadMore = function() {

   // UserService.GetUserRatings($stateParams.id, ?, ?)
   // $scope.ratings.push({...}); This code snippet might be executed within the success block 
   //how do I determine when there are no more results
    $scope.$broadcast('scroll.infiniteScrollComplete'); 
  };

  $scope.ratings = [];

In the view template, you'll see something like this:

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

Answer №1

If you want to update $scope.userRatings, a good approach would be to follow these steps:

  • Start by retrieving the next set of items.

  • Then, add those items to your existing list. It's recommended to use a merge method for this, but without knowing more about your data structure, it's difficult to provide specific advice.

  • I'm not sure how you plan to set noMoreResults to true, but I trust you'll handle that appropriately ;)

.

 var _loopItems = 10;
 $scope.loadMore = function() {
   var _curLength = $scope.userRatings.length;

   UserService.GetUserRatings($stateParams.id, _curLength, _curLength + _loopItems).success(function (data) {
      $scope.userRatings = angular.merge($scope.userRatings, angular.fromJson(data)); // Since I don't know your data format, it's hard to advise on how to merge the values
      }).error(function(error) {
                //do something
    });

    $scope.$broadcast('scroll.infiniteScrollComplete'); 
  };

EDIT: Based on your response:

[{id:1, userid:1, rating_num:5, rating_text:"foo"},{id:2, userid:2, rating_num:5, rating_text:"foo"}]

I recommend updating the merge as follows:

data = angular.fromJson(data);
for (var i = 0; i < data.length; i++){
  $scope.userRatings.push(data[i]);
}

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

Error encountered when importing a Material-UI component: Unable to load a module from @babel/runtime

Struggling to compile the index.js file with rollup: import React from "react"; import ReactDOM from "react-dom"; import Grid from "@material-ui/core/Grid"; ReactDOM.render( <React.StrictMode> <Grid conta ...

When trying to fetch JSON data, the outcome is two pending promises: [ Promise { <pending> }, Promise { <pending> } ]

I am struggling to fetch the JSON data from the API endpoint below: https://api.hatchways.io/assessment/blog/posts When using node.js and making HTTPS requests, I keep getting an array of [ Promise { }, Promise { } ]. The challenge is that I can only se ...

Looking to compare values within an ng-repeat loop?

I am trying to compare values within the context of an ng-repeat directive. Specifically, I need to compare the current value with the previous value in the array being iterated over by ng-repeat. For example, if my array contains the values [2,3], how can ...

Include the url of the html file in your JavaScript code

I have a piece of code that I want to include in my JavaScript instead of HTML. The code is as follows: <script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script> Since all my functions are written in JavaScript, I ...

Unable to perform a POST request and send JSON data using AJAX with jQuery at the

It seems like there may be a server issue causing this problem, and unfortunately, I don't have access to our server to troubleshoot. I was hoping that someone else might have a solution or could help me understand the root cause of the issue. The is ...

What to do when CSS Overflow doesn't work as expected?

Are there any alternatives for browsers that don't support CSS overflow? I am working on a new layout that heavily relies on the overflow property, however it seems like android browsers do not handle it well and as a result, my layout is broken. I am ...

Develop a unique method for loading AngularJS templates

When working with AngularJS, there are various ways to provide an external template, such as using a script tag or a separate HTML file on the web server. However, I am faced with a situation where I need to implement a custom logic for retrieving these ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

Angular directive within a directive

I'm a beginner in AngularJS and I'm attempting to create a directive that contains another directive inside it. Here is how the first directive looks: ( function () { app.directive("cmEventBar", function () { var controller = func ...

Angular JS presents an exciting feature called Multiple Filters, which allows

I have a data representation application that displays information in table format with columns id, name, price, quantity The data is presented using ng-repeat. You can view it on this Plunker <body ng-controller="myController"> <h1>Data< ...

I am curious as to how this function is aware of the specific attribute that is being passed

I've been experimenting with a little application that fetches a list of movies from an API. You input a word and it returns all movies with that word in the title. Here's the code responsible for fetching the list: var getMovies = function (que ...

Utilizing HTML and JavaScript to add grayscale effect to images within a table, with the ability to revert to the colored version upon mouseover

Seeking advice on utilizing the mouseover / mouseout event in javascript to implement grayscale on a table. The challenge requires creating a gray image grid (table) using HTML and then incorporating Javascript so that hovering over an image triggers it to ...

When attempting to install font-awesome with meteor npm, the module 'fontawesome'" was not found

Currently working with meteor version 1.4.1.1 which has NPM support enabled. I encountered an issue after installing the npm package "font-awesome" where the console displayed an error message stating "Uncaught Error: Cannot find module 'fontawesome&a ...

Once the ng-controller is implemented, the state immediately ceases to function

I am encountering a problem when attempting to add a controller to this state. Whenever I include the "ng-controller" attribute, the state ceases to function properly. My goal is to automatically log in a user once they have been authorized through Firebas ...

deleting a class after a function has been executed

Just starting out with Angular and wondering if it's possible to make this change directly in the html: <td ng-class="{'lines-hover': !row.noSpread, 'line-selected': row.spreadSelected}"></td> I current ...

Interpolating backticks in Javascript allows for constructing a URL containing empty spaces

When utilizing string interpolation with backticks to construct a URL that sends data to a django endpoint, the resulting URL contains unnecessary whitespace and a new line. The problematic JavaScript code is as follows: (function (window, document, unde ...

Hiding and displaying DIVs on a single HTML page using VueJs 2

I am currently working on building an application that is not a single page application. As I develop my project, I have several div elements on the page that I want to toggle visibility step by step. Below is the snippet of my code: <div v-if="sect ...

What is the best way to maintain the position of components (such as a Card component) when one is expanded in a Material-UI and ReactJS project

Currently, I am working with an expandable Card component from Material-UI and using flex for aligning the components. However, when one card expands, it affects the positioning of the other components in the row: https://i.stack.imgur.com/vGxBU.png What ...

Setting up an i18n project in AngularJS

I just embarked on my angularjs journey yesterday with little to no prior knowledge about it. My initial goal is to centralize all the labels for my UI in a file (to facilitate swapping them out for i18n). As far as I know, this can be achieved by importi ...

The use of AngularJs with a hash in the href can disrupt scrolling functionality and alter the URL to include a combination of hash

How can I make AngularJs scroll to a specified anchor element using the href attribute with an #id? The issue When using an anchor link with a hash, like href="#recommanded", it becomes url#/recommanded instead of url#recommanded, causing it not to scrol ...