Tips for showing a limited number of results the first time in an AngularJS application

I am a beginner in AngularJS and Ajax requests. I created a demo where I make an Ajax request to get remote data and display it in a list. My goal is to initially show only 10 results when the page loads for the first time, and then load the next 10 results as the user scrolls down.

I also created another demo, but it continues to load infinite lists, making unnecessary HTTP requests each time. I want it to make only one HTTP request and display 10 results at a time. It should only fetch more results when the user scrolls down to request the next set of 10.

Below is my code:

HTML

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        
          <link rel="stylesheet" href="mycss.css">
         
               <script src="angular/angular.js"></script>    
  <script src="angular/angular-touch.js"></script>  
  
   <script src="app.js"></script>    

    </head>
   
    <body>
      
        
        <div data-ng-app='demo'>
  <div data-ng-controller='MainController'>
    <ul class='hello' when-scrolled='more()'>
      <li data-ng-repeat='item in items'>
        {{item}}
      </li>
    </ul>
    <div data-ng-show='loading'>Loading</div>
  </div>
</div>
<h1>INFINITE SCROLLING IN ANGULARJS</h1>
    </body>
</html>

JavaScript

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var caymanauth ='MTIzNDU2ODk6ZUVqVFpmcnRJMQ==';
app = angular.module("demo", []);
var API_HOST ='http://caymanafterwork.netcluesdemo.com/beta';
app.controller("MainController", function($scope, $http) {

  // the array which represents the list
  $scope.items = ["1. Scroll the list to load more"];
  $scope.loading = true;

  // this function fetches a random text and adds it to array
  $scope.more = function() {
    $http({
//      method: "GET",
//      url: "https://baconipsum.com/api/?type=all-meat&paras=2&start-with-lorem=1"

 method: 'POST',
            url:  API_HOST+'/webservice/listinglist',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'caymanauth': caymanauth
            },
                                  data: "&Start="+0+"&Pagesize="+6+"&SearchTxt="+''+"&FilterTxt="+''+"&FilterStarSearch="+''+"&FilterPriceSearch="+''+"&FilterLocationSearch="+''+"&FilterCuisineSearch="+''+"&FilterCategorySearch="+''+"&FkCategory=1"
          
    }).success(function(data, status, header, config) {
        console.log("========my response is=============",data);
      // returned data contains an array of 2 sentences
//      for (line in data) {
//        newItem = ($scope.items.length + 1) + ". " + data[line];
//       $scope.items.push(newItem);
//      }

   for (var i = 0 ; i< data['Details'].length ; i++)
            {
              
                      var newItem =  ($scope.items.length + 1) + ". "+data['Details'][i]['varTitle'];
           $scope.items.push(newItem); 
         
             $scope.loading = true;
                    
            }
                        $scope.loading = false;
              
    
    });
  };

  // we call the function twice to populate the list
  $scope.more();
});

// we create a simple directive to modify behavior of <ul>
app.directive("whenScrolled", function() {
  return {

    restrict: 'A',
    link: function(scope, elem, attrs) {

      // we get a list of elements of size 1 and need the first element
      raw = elem[0];

      // we load more elements when scrolled past a limit
      elem.bind("scroll", function() {
        if (raw.scrollTop + raw.offsetHeight + 5 >= raw.scrollHeight) {
          scope.loading = true;

          // we can give any function which loads more elements into the list
          scope.$apply(attrs.whenScrolled);
        }
      });
    }
  }
});

Answer №1

Check out ui-scroll for a potential solution.

This tool serves as an alternative to ngRepeat and is designed to provide the desired functionality.

Answer №2

We implemented a custom directive that listens to the scroll event of the browser window and triggers a function in the scope to fetch new data.

Alternatively, you can also explore examples at or visit .

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

Vite deciding to generate its own node_modules directory within the workspace rather than depending on a monorepo

I have organized a monorepo for a fullstack webapp with the directory structure outlined below: . ├── client │ ├── index.html │ ├── package.json │ ├── src │ └── vite.config.ts ├── node_modules ├── p ...

Installation Failure: Angular-CLI/Chokidents Partnership Error

Newest Node version is 6.7.0 Encountered an error during installation stating notsup not supported by this operating system Operating System: Windows 10 https://i.sstatic.net/jwge3.png ...

execute field function prior to sorting

Currently, I am building a graphql server in express and using a resolver to modify my fields based on user input from the query. The issue arises from the transformer function returning a function. My goal is to sort the results by a field determined by ...

Comparison between the sluggishness of radio buttons in Internet Explorer 10 versus Chrome when using jQuery

When using IE 10, Chrome, and jquery 1.10.2 with the standard template from Visual Studio 2013 (.Net 4.5), I encounter an issue with radio buttons. Upon clicking a radio button, two actions are supposed to occur: 1. Recreation of all the radio buttons. 2 ...

How to dynamically assign a value in a React datepicker component in a React application

Having troubles with react-datepicker? I encountered an issue where setting the value of react-datepicker from props caused it to either not show the value or display a 'wrong time format' error. Here is a snippet of the Datepicker code: this.sta ...

Is a JS-Native Bridge that works across all platforms?

Currently, I am developing an app that heavily utilizes webviews on both iOS and Android to display content with native chrome around it. I am looking for a way to manipulate this chrome using JavaScript methods. On Android WebView, there is a feature cal ...

When the Next js page loads, it briefly displays a 0 at the top for a moment before loading the rest

When my nextjs app loads a page, there is a momentary appearance of a 0 in the top left corner. This happens even if I am fetching data from Sanity CMS using getStaticProps and returning content. Interestingly, I have observed that simply returning an empt ...

Maximizing the potential of Next JS 13 Server Components

Exploring the updates in Next JS 13, I have found it intriguing that every component is now a server component by default. This concept has been puzzling for me as I try to grasp how to effectively leverage this feature. For instance, my current challenge ...

Indeed, yet another problem with clearInterval

I could use some assistance as I am currently stuck trying to figure out why the stopTimer() function is not working correctly. Any guidance or suggestions would be highly appreciated. Thank you! http://jsfiddle.net/4Efbd/1/ var counter; function endTim ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

Ways to access nested keys in a TypeScript object as well as an array containing objects

As I develop a form generator, my goal is to achieve type safety for a nested object and an array of objects. Specifically, I want the 'name' property to correspond to the key of the respective object it belongs to. For instance, in the scenario ...

Creating responsive images in a navbar with HTML and CSS

I need help with this code snippet: <div> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <div class="d-flex flex-row justify-content-center align-items-center"> <a cla ...

When running the test, the message "Unable to resolve all parameters for BackendService" is displayed

Upon executing the ng test command, the following error was displayed. This is my service specification: describe('BackendService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { p ...

Challenges with handling Ajax responses in Ruby on Rails

I'm currently facing an issue with the Ajax response in my Rails application, and I'm unsure of how to troubleshoot it. Here is the code that is functioning correctly: View <div id="<%= dom_id(comment) %>_count"> <%= Like.wh ...

Encountering an issue with setting up Pinia in Vue3, as it is showing an error message stating "

I am facing a challenge with my Vue app where the normal reactive store is not working correctly and does not retain the values I have set. Hence, I would like to switch to a Pinia store. After installing Pinia, my main.js file looks like this: import { cr ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

Difficulty arises when attempting to run code when a checkbox is not selected

In my form validation process, I am facing an issue where I need to validate certain values only if a checkbox is unchecked. If the checkbox is checked, I want to use the values that were previously added. However, none of the existing code snippets seem t ...

Adjust the NVD3 line chart grid

I am currently working on a project that utilizes the NVD3 lineChart, but I am facing difficulty in editing the chart's grid. Here are the chart's options: chart: { type: 'lineChart', height: 430, margin: { ...

Detection of numerous Google Analytics tags

To troubleshoot a client's Google Analytics account connected to their website, I decided to utilize the Tag assistant by Google extension. Upon running it, an alert popped up displaying "Multiple Google Analytics tags detected." One tag was the one I ...

Trouble with formatting credit card numbers in Vue.js

My payment gateway component includes a feature where selecting credit card triggers the _formatCreditCard method to format the credit card number like this: 4444 2442 4342 3434 This is the function in question: _formatCreditCard: function() { var n ...