Leverage AngularJS $http.get method to continuously fetch JSON array upon scrolling

Here is a snippet of code that utilizes AngularJS to retrieve a JSON response.

I am looking for assistance in implementing a functionality where the page should make additional requests when the user scrolls to the bottom, continuing until the JSON array list is depleted.

<section>
        <div style="padding-top:60px" infinite-scroll="myPagingFunction()" infinite-scroll-distance="3" ng-app="myApp" ng-controller="myCtrl"> 
            <div ng-repeat="news in newsList">

                <div class="col-lg-3 col-md-4 col-sm-6" style="">
                    <div class="thumbnail">
                        <img src="{{news.coverUrl}}" class="img-responsive"  alt="{{news.name}}"/>
                        <div class="caption">
                            <h4>{{news.name}}</h4>
                        </div>
                    </div>
                </div>
                <div class="visible-lg clearfix" ng-if="($index+1)%4 == 0"></div>
                <div class="visible-md clearfix" ng-if="($index+1)%3 == 0"></div>
                <div class="visible-sm clearfix" ng-if="($index+1)%2 == 0"></div>

            </div>
        </div>
    </section>
    <script src="js/jquery.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="js/ng-infinite-scroll.min.js"></script>


    <script>
        var offset = 0 
        var maxCount = 20
        var app = angular.module('myApp', ['infinite-scroll']);
        function myPagingFunction(){

            app.controller('myCtrl', function($scope, $http) {
                $http.get("news.json").then(function(response) {
                  $scope.newsList = response.data; 
                });
            });
        }
        myPagingFunction();
    </script>

    <script src="js/bootstrap.min.js"></script>

If you have any insights or guidance on how to achieve this functionality, I would greatly appreciate your help.

Answer №1

Avoid combining jQuery with Angular at all costs. It's best to stick to the Angular methodology and create custom directives or listeners within the 'run' phase. Alternatively, consider implementing the `ngInfiniteScroll plugin for a more efficient solution.

Answer №2

If you want to make achieving this task easier, consider utilizing infinite scroll services.

    <ANY infinite-scroll='{expression}'
 [infinite-scroll-distance='{number}']
 [infinite-scroll-disabled='{boolean}']
 [infinite-scroll-immediate-check='{boolean}']
 [infinite-scroll-listen-for-event='{string}']>

To learn more and effectively implement this feature, make sure to integrate the ng-infinite scroll module into your application. For detailed instructions, refer to the official documentation:

Answer №3

Implement this straightforward directive to enhance your browsing experience:

app.directive("scroll",['$window', function ($window) {
return function (scope, element, attrs) {
    angular.element($window).bind("scroll", function () {

        if (document.body.scrollHeight - $window.scrollY < 890) {
            scope.$apply(function () {

                scope.myPagingFunction();
            });
        }

    });
};
 }]);

You can apply the provided code to suit your specific needs

    <section>
        <div style="padding-top:60px" scroll ng-app="myApp" ng-controller="myCtrl"> 
            <div ng-repeat="news in newsList">

                <div class="col-lg-3 col-md-4 col-sm-6" style="">
                    <div class="thumbnail">
                        <img src="{{news.coverUrl}}" class="img-responsive"  alt="{{news.name}}"/>
                        <div class="caption">
                            <h4>{{news.name}}</h4>
                        </div>
                    </div>
                </div>
                <div class="visible-lg clearfix" ng-if="($index+1)%4 == 0"></div>
                <div class="visible-md clearfix" ng-if="($index+1)%3 == 0"></div>
                <div class="visible-sm clearfix" ng-if="($index+1)%2 == 0"></div>

            </div>
        </div>
    </section>
    <script src="js/jquery.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="js/ng-infinite-scroll.min.js"></script>


    <script>
        var offset = 0 
        var maxCount = 20
        var app = angular.module('myApp', ['infinite-scroll']);
         app.controller('myCtrl', function ($scope, $http) {
    $scope.myPagingFunction= function() {
        $http.get("news.json").then(function (response) {
            $scope.newsList = response.data;
        });
    }
             });
    app.directive("scroll",['$window', function ($window) {
  return function (scope, element, attrs) {
angular.element($window).bind("scroll", function () {

    if (document.body.scrollHeight - $window.scrollY < 890) {
        scope.$apply(function () {

            scope.myPagingFunction();
            });
        }

    });
};
}]);
    </script>

    <script src="js/bootstrap.min.js"></script>

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

How can I code a script to import JSON data into MongoDB database?

I have a JSON file named "data.json" that contains an array of people's names as shown below: "data": [ { { "name":"John", "age":30, } { "name":"Mark", "age":45, } } ] I am ...

Using Ajax to return a Post type in c# mvc 4 instead of a value

Hey there, I seem to be encountering an issue that I could use some help with. $.ajax({ type: "POST", url: "/controller/CreateList", contentType: "application/json; charset=utf-8", traditional: true, ...

What is the best way to display a nested JSON object structure?

{ "Title": "Jurassic Park", "Year": "1993", "Rated": "PG-13", "Released": "11 Jun 1993", "Runtime": "127 min", "Genre": "Action, Adventure, Sci-Fi", "Director": "Steven Spielberg", "Writer": "Michael Crichton, David Koepp", "Actors": "Sam ...

Utilize the power of jQuery to easily toggle visibility of an overlay

I have successfully implemented JQuery to show and hide my overlay with great success. Now, I am interested in adding animations to enhance the user experience. After reviewing the jq documentation, I found some cool animations that can be easily integrate ...

extract data from a JavaScript object

Currently facing an issue extracting a String name from the JSON object's name. It is necessary to parse this type of JSON response obtained from the server. var response = { hopaopGmailsjIpW: { GmailsjIpW_totalEmails_count: 133, GmailsjIpW ...

"What is the best approach to adjusting the width of one div based on the width of another div using CSS Grid

As a beginner in programming, I'm trying to work with CSS Grid but facing some challenges. My goal is to create a component with two columns: the left column should have a width of minmax(570px, 720px), and the right column should be minmax(380px, 10 ...

Is it possible to interpret all events from multiple perspectives?

Is it possible to listen for events in three different ways? This example shows how we can listen for the load event: 1. <body onload="doSomething();"> 2. document.body.onload = doSomething; 3. document.body.addEventListener('load', doS ...

Is there a way to prompt WebAPI to receive a complicated object as its argument for a DELETE HTTP request without relying on C# attributes?

Currently, my server is utilizing C#/WebAPI while the client side is using AngularJS. I am faced with a dilemma when it comes to formatting an HTTP DELETE request without specifying attributes in C#. Specifically, I am struggling with how to handle a meth ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox <a href="https://codesandbox.io/p/github/cloudmako09/btu-calc/main?im ...

Adding elements to a global array via a callback function in JavaScript: A step-by-step guide

I am currently working on querying and adding users to a global array from my database. My goal is to store the elements in this global array so that I can access it from any part of my application. app.get("/admin/orders", (req, res) => { Q ...

Having difficulty engaging with external AngularJS application using PhantomJS and Capybara

Having trouble interacting with an AngularJS third party application despite installing capybara-ng, capybara/angularjs and switching to the AngularJS DSL. My setup includes ruby2.0.3 and phantomjs-2.0.0-windows. The DOMs are not fully loaded, preventing ...

Does anyone know of a CSS/JavaScript framework that can be used to replicate the look and functionality of the iOS home

I'm wondering if there is a CSS/JavaScript framework that replicates the layout of an iOS home screen. I want to create a kiosk website with a grid layout similar to Android/iOS where apps can be displayed as icons. ...

Learn the process of submitting a request and saving a file to disk using Angular

When working with Angular, I am looking for a way to download a text file containing a CSV of user data without requiring the page to refresh. Typically, I would use a form with a post action, but in this case, I want the user to remain on the same page wh ...

The Evolution of Bulma's Navigation Menu

Creating a transparent menu in Bulma has been successful for the desktop viewport: VIEW DESKTOP MENU However, when attempting to implement the same design on mobile, the menu ends up like this: VIEW MOBILE/TABLET MENU The mobile version seems to inheri ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

Incorporate an Ajax request onto an existing link within a div element

Here is what I have: <div id="div-for-ajax-onclick"> <a href="http://www.google.com">Link to google</a> </div> $("#div-for-ajax-onclick").click(function() { // update database }); I am looking for a solution where if someone c ...

What is the process of utilizing an npm package as a plain JavaScript library through require and module export?

Hey there, I'm a bit unsure if I'm on the right track with my question, but here it goes: What steps do I need to take to modify a node.js package for use as a standalone embedded script/library in HTML? How can I invoke a class constructor in ...

Determine the height of an element in JavaScript or jQuery by using the CSS property height: 0;

I'm facing a challenge in determining the actual height of an element, which currently has a CSS height property set to: height: 0; When I check the console, it shows a height of 0, but I'm looking to find the real height of the element. I als ...

Is there a way to verify the presence of a complete object by using a specific key in JavaScript

As I loop through my data, I only want to assign a random number to a fontObj if it is unique. A typical fontObj consists of: { postscript: "Calibri", style: "Bold", family: "Calibri" } In my code, I aim to iterate ...

What is the best way to implement a gradual decrease in padding as the viewport resizes using JavaScript

My goal is to create a responsive design where the padding-left of my box gradually decreases as the website width changes. I want the decrease in padding to stop once it reaches 0. For instance, if the screen size changes by 1px, then the padding-left sh ...