Arranging by and loading progressively in AngularJS

Encountering an issue with the orderBy function in an ng-repeat paired with an auto-incrementing limitTo. After loading a few elements on the page, the directive ceases to function properly and stops increasing the element limit.

Here is the HTML code snippet:

<div class="row" id="main">
        <div class="col-xs-12 col-sm-6 col-md-3 col-lg-2 block animate"
             ng-if="!errorDialogActive"
             ng-repeat="build in builds.builds.build | limitTo:totalDisplayed | orderBy:'lastBuildDetails.startDate' : true track by build._id"
             ng-class="{'running': project.running ,'block-green': build._status ==='SUCCESS','block-red': build._status==='FAILURE'}"
             id="{{build._id}}"
             progressive-loading>
            <div class="title-container animate" ><p>{{build._buildTypeId}}</p></div>
            <div class="update-container animate col-xs-12">
            <time class="time">{{build.buildDate | date : 'dd.MM.yyyy H:mm:s'}} </time>
            </div>
        </div>
    </div>

Here is the directive code:

return function (scope) {
    if (scope.$last) {
        $timeout(function () {
            console.log('Im the last Displayed, Loading more');
            scope.loadMore();
        }, 100);
    }
};

And this is the loadMore function:

    $scope.loadMore = function () {
        if ($scope.totalDisplayed >= $scope.size) {
            console.log('no more builds : ' + $scope.totalDisplayed);
            $scope.loaded=true;
        } else {
            $scope.totalDisplayed += 2;
            console.log('More : ' + $scope.totalDisplayed);
            $scope.totalDisplayedPercentage = (($scope.totalDisplayed*100)/$scope.size);
            console.log('Percentage : ' + $scope.totalDisplayedPercentage);
        }
    };

Apologies for any language barriers. If further clarification or details are needed, please feel free to reach out.

Answer №1

When implementing the directive link function, it is crucial to consider the behavior of the orderBy function. If a new rendered element is placed in the middle, the special property scope.$last will be false, indicating that the element is not the last one. In such cases, it is unnecessary to start a timeout.

To address this issue, you can create a counter to track the displayed elements. Below is a basic example:

app.directive('progressiveLoading', ['$timeout', function ($timeout) { 
    var counter = 1;
    return function (scope) { 
        if (counter == scope.displayStep) { 
            counter = 1;
            $timeout(function () { 
                console.log('Im the last Displayed, Loading more'); 
                scope.loadMore(); 
            }, 500); 
        } else {
            counter += 1;
        }
    }; 
}]);

Here is a simplified version:

// Code goes here
var app = angular.module('app', []);

app.directive('progressiveLoading', ['$timeout',
  function($timeout) {
    var counter = 1;
    return function(scope) {
      if (counter == scope.displayStep) {
        counter = 1;
        $timeout(function() {
          console.log('Im the last Displayed, Loading more');
          scope.loadMore();
        }, 500);
      } else {
        counter += 1;
      }
    };
  }
]);

// Controller code
// HTML code

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

Combining JS Tree and Datatables for Enhanced Functionality

I am facing a challenge on my webpage where I have two columns. The left column consists of a checkbox jstree, while the right column contains a table using datatables. Both the table rows and tree are loaded at the start. My goal is to display a row when ...

Showing child elements within a div using AngularJS

I am eager to create a straightforward AngularJS website that will showcase an initially hidden HTML element along with all of its children. Below is the HTML structure snippet I plan to use: <div class="hiddenStuff"> <h3>Game Over</h3&g ...

Guide to smoothly transition the highlighted <tr> element to the top of the scroll bar

Is there a way to utilize jQuery for animating a selected row to the top of a div with a specific scrollbar style? #sc { border:1px solid black; width:450px; height:80px; overflow:scroll; } <div id="sc"> <table id=&quo ...

When attempting to access the length of a JSON array, it results in undefined

I recently received a JSON encoded array from an AJAX call that looks like this: {"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}} Below ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

The default theme has not been specified in Tailwind CSS

During my recent project, I utilized React, Next.js in combination with Tailwind CSS. In this project, I delved into styling customization by implementing react-slick for a specialized slider. To achieve the desired aesthetic, I made modifications to the r ...

Error: The server selection process has encountered an unexpected issue

Embarking on my journey with MongoDB and the MERN stack, I turned to these tutorials for guidance: https://medium.com/@beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1 https://www.youtube.com/watch?v=7CqJlxBYj-M ...

Is it possible to restrict contenteditable elements to only accept numbers?

Is there a way to restrict contenteditable elements such that only numerical values can be entered? I attempted to use the following code snippet: onkeypress='return event.charCode >= 48 && event.charCode <= 57' However, despite a ...

What is the best way to configure the loading state of my spinner?

When a user clicks to navigate to the articles page, I want to display a spinner while waiting for the articles data to be fetched and displayed. There is a slight delay after the click, hence the need for the spinner. I have a custom spinner component ca ...

"Step-by-step guide to updating user information in MongoDB with the help of node.js

I have been working on a basic express app with MongoDB integration, allowing users to register, log in, and log out successfully. However, I am facing an issue when attempting to implement the functionality to edit user data. The code runs without any err ...

Divide a JavaScript project into multiple packages using either webpack or npm

I am embarking on the development of an application that needs to be compatible with Windows (PC), Android, and iOS. To achieve this, I plan to use Electron for Windows and React Native for mobile platforms. Both applications will be built using React and ...

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...

Is it possible to extract information from a string that includes HTML code within a browser using CSS selectors without actually generating the DOM elements?

I've been struggling with this basic task for hours. I can't find any libraries that work and none of the questions here address my specific issue. Here's what I need to do: The entire page's markup is in a string format. I must use ...

Ways to set control values with AngularJS

After retrieving a single record from the database for my detail view, I need to assign data to controls. Take a look at my code snippet below: var app = angular.module("MyProductApp", []); app.controller("ProductsController", function ($scope, ...

What could be causing the malfunction with Angular?

What seems to be the issue? <!doctype html> <html lang="en" ng-app='SOO'> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div ng-controller='someController ...

Remove properties that are not part of a specific Class

Is there a way to remove unnecessary properties from the Car class? class Car { wheels: number; model: string; } const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'}; const goodCar = filterUnwant ...

Check if there are any child nodes before executing the RemoveChild JavaScript function to avoid any errors

function delete(){ let k = document.getElementsByClassName('row'); for(let i=0; i<k.length; i++) { if(k[i].hasChildNodes()){ k[i].removeChild(k[i].childNodes[2]); } } } <div id="table"> <div class="row"& ...

How can I update the value of a span element that was added to the HTML document through an AJAX request?

When a modal is triggered on click, data is added to it through an AJAX request to a PHP file. After the AJAX call, I want the values in span elements within the modal to change simultaneously with the input field of the modal. I attempted this JavaScript ...

Avoiding page refresh when clicking on a button component in React

Apologies if this question has already been addressed. I've done my research but I might be missing something. Currently, I'm working on a React app and I want to ensure that my buttons do not reload the page, but only refresh the state. Here&ap ...

Guiding the user to a different React page after a successful login: a simple solution

Currently, I am working on developing my very first full-stack application with React for front-end and Node.js with Express for back-end. I have set up a /login route using react router dom where users can input their email and password ...