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

Preventing ngclass animation in Angular 1.2 from running when re-compiled

Example: http://codepen.io/anon/pen/ixEdu I am currently working on an angular animation using ngClass. In the scenario where the element containing the animation is re-compiled, the animation triggers again. Is there a way to prevent this unwanted behavi ...

How to use AngularJS ng-options to retrieve the chosen option from an array that corresponds to another variable in the scope

Does anyone know how to create a dropdown select in AngularJS with default selection based on a dynamic value? $scope.fcFeedTypes = [{"name":"Plain Text","value":"Plain Text"},{"name":"MQ Message","value":"MQ Message"}]; } $scope.feedEditor.ft = "MQ Messa ...

Step-by-step guide on deploying an Angular and Express project to Google App Engine

I am in the process of deploying my app to Google App Engine. I have already set up App Engine and installed gcloud on my local machine. While I have been successful in deploying some projects, I have only done so for Angular applications. My goal now is ...

How to Load JSON Data Using D3 When Column Definitions are Separated

I'm currently working with d3.js and struggling to grasp how I can effectively load a JSON file representing a table that has separate column definitions. A typical JSON file, which I have no issue loading, might appear like this: [ { "id": 1, ...

Is there a way to incorporate a Laravel foreach loop within a JavaScript file?

I recently added a select-box using jQuery: <span onclick="createProduct()">Add New<i class="fa fa-plus"></i></span> <script> function createProduct() { var html = ''; html += ' <div clas ...

What is the purpose of parsing my array if they appear identical in the console?

While working on a D3 component, I came across an interesting question. Why do different arrays require different data treatment even if they all contain the same information? In the first case, I have a 'hardcoded' array that looks like this: ...

Send the Post model along with 2 checkbox lists to the controller using Jquery's Ajax function

How can I efficiently send 2 lists containing values of checked checkboxes along with my model using JQuery Ajax from an EditorTemplate used as a partial view? Here's the code snippet: @model EsdpExport.View_Models.ProductLineCreateViewModel @using E ...

The click functionality is not functioning properly within the .each() loop

For my event handler, I am trying to use click() but it doesn't seem to be working. Here is the code snippet: $('.ajax-close').click(function( event ){ event.preventDefault(); alert('hi'); $( ' ...

Instructions for setting attributes on the ngForm object within a component class

My form data is represented as a JSON string using JSON.stringify(form.value) and it currently looks like this: "body":{ "panNo":"IRFPP1993A", "ackNo":"123456789" } I would like to modify the output to include an additional value, making it look like thi ...

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 ...

ReactJS encountering an invalid dropzone element

Encountering the error "invalid dropzone element". I added var Dropzone = require('react-dropzone'); to my webpack.config.js file in hopes of activating the Dropzone element. This is what is included in my JavaScript file, copied from a Gith ...

What is the process for switching directories and renaming a file when uploading in nodeJs?

I am currently using multer and fs to handle the upload of an image file. How can I modify the directory where uploaded files are stored? Currently, all files are saved in my "routes" folder instead of the "uploads" folder created by multer. Additionally, ...

Enhance your SVG path by allowing users to drag points on Quadratic or Cubic Bezier curves

In my project, I am trying to make it so that when a user drags the point, it always stays aligned with the path. The goal is for the command Q, C, or S to adjust the curve based on the position of this draggable point, rather than treating it as a control ...

Display Issues with Angular Material Dropdown in Internet Explorer 11

How can I fix the display of Angular Material Dropdown in IE11 to match other browsers? Expectation: https://i.sstatic.net/IksBR.png Reality in IE11:https://i.sstatic.net/uhHXG.png Website information: [example no longer available. AngularJS was replace ...

What could be causing the abundance of API calls from Yandex Metrica?

In my Nextjs SPA, there is an iframe widget that is rendered using React. Inside this widget's index.html file, I have inserted the Yandex Metrica script and set up a goal tag to track user clicks on the registration button. The goal tracking is wor ...

Apply a specific style conditionally using Angular's ng-repeat directive

Currently, I am utilizing ng-repeat to iterate through a list of divs and manually adding items to the JSON that is rendering these divs. My goal is to position the last div that I add in the JSON at the location where the mouse cursor is, while keeping th ...

"Encountering a problem with compression in Kafka while using the Node.js client with

I am currently utilizing the kafka-node library to consume data from Kafka. It appears that the data I am receiving is compressed with SNAPPY. How can I decompress this data once it has been retrieved? I attempted to use the node-snappy library for decompr ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

The function toggleClass() is malfunctioning

The .toggleClass() method seems to only be adding the "class" attribute to my selection, resulting in: <div id="toggle" class> ... rather than: <div id="toggle" class="on"> ... I've been trying to solve this issue for about 2 hours now ...

The Javascript slider fails to function properly when utilizing AJAX to load the page

I have encountered an issue while trying to open an HTML page using ajax when a button is clicked. The HTML page that I am opening contains a JavaScript slider that functions properly when opened individually, but stops working if opened through my index. ...