Can you explain the functionality of this Sample AngularJS Infinite Scroll feature?

I stumbled upon this AngularJS script while searching for some samples, but I'm having trouble understanding the angular module and directive aspects of the code. However, I did manage to modify the loadMore() function to fetch a JSON resource from my RESTful API and it's working well with the infinite scroll feature. Could someone kindly explain how this all works? I've just started learning and experimenting with AngularJS in my free time over the past week...

Original source: http://jsfiddle.net/vojtajina/U7Bz9/

function Main($scope) {
    $scope.items = [];

    var counter = 0;
    $scope.loadMore = function() {
        for (var i = 0; i < 5; i++) {
            $scope.items.push({id: counter});
            counter += 10;
        }
    };

    $scope.loadMore();
}

angular.module('scroll', []).directive('whenScrolled', function() {
    return function(scope, elm, attr) {
        var raw = elm[0];

        elm.bind('scroll', function() {
            if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                scope.$apply(attr.whenScrolled);
            }
        });
    };
});

My modified version:

function Main($scope, $http) {

    $scope.phones = [];

    $scope.loadMore = function() {
        $http.get('http://www.somewhere.com/api/phones').success(function(data) {
            if($scope.phones.length > 0) {
                $scope.phones = $scope.phones.concat(data);
            }
            else {
                $scope.phones = data;
            }
        });
    };

    $scope.loadMore();
}

Answer №1

Let me take a shot at explaining this:

This specific declaration creates a link function that will run for every instance of the directive. This means it will execute when the page loads and attach an event listener to each list item when scrolled. If the height calculation is true, it will add an attribute called "whenScrolled" to the current li element, prompting Angular to recompile the DOM and process the new directive. As a result, the loadMore() function will be triggered, appending additional items to the list.

The use of $apply here is crucial because Angular won't automatically handle the newly added directive on the list item, causing our scroll handler not to be included.

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

Performing a simulated click on a dynamically inserted element using pure JavaScript

I am faced with the challenge of programmatically navigating a ReactJS-based website in a looped workflow. The process involves clicking on Element1, dynamically altering the web page to add Element2, then clicking on Element2, and so on until eventually r ...

Disable checkboxes upon page initialization

I am working with a form that includes checkboxes. Whenever the page loads, clicking on the checkboxes automatically checks them. However, I am looking for a solution where the checkboxes are disabled or not clickable during the page load process. Once th ...

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

Tips for detecting a new day with server-side JavaScript

I am currently developing a website that includes a schedule for teachers. I have encountered the need to delete elapsed days data from a database. What is the most effective method to monitor when it is exactly 12 midnight? If I were to use setInterval( ...

Integrate JavaScript code with HTML pages

After creating a basic HTML structure that I am proud of, I encountered some challenges with getting the Javascript to function properly. I am new to working with Javascript and received some initial assistance, but unfortunately, it is no longer working. ...

Is it possible to ensure that an asynchronous function runs before the main functional component in React js?

My challenge involves extracting data from an API by manipulating a URL. Specifically, I must retrieve a specific piece of information upon page load and then incorporate it into my URL before fetching the data. var genre_id; var genre; const MOVIE_URL = ` ...

Receiving JSON objects from Javascript in Django Views

When I attempt to pass a Json Object value from making an API call to my views.py in Django template, I encounter difficulty retrieving the value after an ajax call. let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = a ...

Having trouble with your jQuery code not loading properly?

Currently working on debugging jQuery code and facing an issue where a particular section of the code is not being triggered upon clicking. The HTML/PHP in question: $cartlink .= "<a class='add_to_cart button' data-id='{$product->id} ...

My ReactNative Android application is experiencing significant lag, is there anyone who can assist me in resolving this issue?

Currently, I'm tackling a reactnative android app project and have noticed a significant drop in performance. Unfortunately, I am clueless about the root cause of this issue. Could it be related to the navigator or are there other underlying factors a ...

Tips on avoiding scrolling when toggling the mobile navigation bar:

While working on a website using HTML, CSS, and BS3, I have created a basic mobile navigation. However, I am facing an issue where I want to disable scrolling of the body when toggling the hamburger button. The problem arises when the menu is toggled on, ...

What is the best way to include a new class into the current class in this particular scenario?

Just starting out with Javascript and Jquery, so please bear with me if this question seems basic I'm dynamically constructing HTML like this: var favoriteresultag = '<ul>'; favoriteresultag += "<section id='"+name+"' ...

While attempting to utilize inner class functions in Node JS, an error is being encountered

I've been delving into Node JS and exploring how to implement an OOP structure within node. I've created a simple class where I'm using functions to verify and create users in a database. However, I'm encountering a TypeError when attem ...

What is the method for adding a tag within a specific div ID in ExtJS?

I am looking to insert a new tag within existing tags using extjs, based on the div id 'task123', and also trigger an alert message accordingly. Below is the HTML code snippet: <div id="task123"> <div class="msg" id="sample"> ...

How can one use C# and Selenium to send text to a hidden textarea with the attribute style="display: none;"?

I'm encountering an issue where I am unable to write in the textarea using the sendkeys function in Selenium. The specific textarea I am trying to target has an ID of 'txtSkillsTaught-Value' and is located after a script tag that seems to be ...

Angular Material's floating add button feature bears a striking resemblance to the one found

Is there a way to create a design similar to the image below using Angular Material? https://i.stack.imgur.com/L3zvH.png ...

Arrangement of Bootstrap card components

Each card contains dynamic content fetched from the backend. <div *ngFor="let cardData of dataArray"> <div class="card-header"> <div [innerHtml]="cardData.headerContent"></div> </div> <d ...

Ways to speed up the initial loading time in Angular 7 while utilizing custom font files

Storing the local font file in the assets/fonts folder, I have utilized 3 different types of fonts (lato, raleway, glyphicons-regular). https://i.stack.imgur.com/1jsJq.png Within my index.html under the "head" tag, I have included the following: <lin ...

Establishing the highest allowable value limit in cleave

I've integrated cleave.js into my Vue.js project to create a date input field. Here's the option configuration I used: <cleave :options="{ date: true, datePattern: ['m', 'd','Y'] ...

The `res.send()` function is showing [object object] and I am unable to access any properties

I've just started learning about REST APIs with express. I am encountering a strange issue where the code successfully console logs { name: 'Test', id: 1 } for the user, but when I send the response, it displays [Object object]. Additionally ...

What methods are available for drawing on an HTML canvas using a mouse?

I am facing two challenges: how can I create rectangles using the mouse on an HTML canvas, and why is my timer not visible? Despite trying various code snippets, nothing seems to be working. Grateful for any help! HTML: <!DOCTYPE html> <html lan ...