Angular JS effectively prevents redundant data from being displayed to users when scrolling infinitely while also efficiently removing DOM elements for previous data

I'm currently working on implementing AngularJS Infinite Scroll without using jQuery. My goal is to display the first 3 data items when the page loads and then load the next 3 data items from a JSON array object as the user scrolls. The issue I am facing is that while I can successfully load the initial 3 data items, when scrolling, it repeats loading the first 3 items instead of showing the next set. Additionally, I want the scroll functionality to show the next set of data when scrolling down and the previous set when scrolling up (similar to a pagination concept).

Below is the array used to parse the data in the controller:

var app = angular.module('Demo', []);

app.controller('VerticleDemo', function($scope) {

  $scope.items = [];
  $scope.Arr = [{
    "Select": "11",
    "PhotoCount": "12"
  }, {
    "Select": "21",
    "PhotoCount": "22"
  }, {
    "Select": "31",
    "PhotoCount": "32"
  }, {
    "Select": "1",
    "PhotoCount": "1"
  }, {
    "Select": "71",
    "PhotoCount": "72"
  }, {
    "Select": "441",
    "PhotoCount": "90"
  }, ];

  $scope.addItems = function() {
    for (var i = 0; i < 3; i++) {

      $scope.items.push($scope.Arr[i]);

    }
  };


  $scope.addItems();
});
    .scroll-loader {
      background: #f7f7f7;
      height: 90px;
      border: 3px solid #d2d2d2;
      margin-bottom: 20px;
      overflow: auto;
      padding: 10px 0;
      border-radius: .5rem 0 0 .5rem;
    }
    .scroll-loader li {
      list-style: none;
      border-bottom: 1px solid #aaa;
      padding: 5px;
      margin-bottom: 3px;
    }

I've been struggling with eliminating duplicate data and have tried various solutions without success. You can find my jsFiddle link below for reference: https://jsfiddle.net/sathishkti/96qhssfe/15/ Any help or guidance on resolving this issue would be greatly appreciated.

Answer №1

The issue lies within your addItems() function:

Your code is consistently adding items 0 to 3, but the desired behavior should involve creating an offset variable that allows you to skip over items that have already been displayed. You can increment this offset by a value of X every time your scroll event is triggered. To simplify things, I've stored the number 3 in a variable, but it's advisable to include this as part of the directive so that it can be easily adjusted in the HTML for greater flexibility.

var app = angular.module('myApp',[]);
app.controller('tstrll', function($scope) {

  $scope.items = [];
  $scope.Arr = [{
    "Select": "11",
    "PhotoCount": "12"
  }, {
    "Select": "21",
    "PhotoCount": "22"
  }, {
    "Select": "31",
    "PhotoCount": "32"
  }, {
    "Select": "1",
    "PhotoCount": "1"
  }, {
    "Select": "71",
    "PhotoCount": "72"
  }, {
    "Select": "441",
    "PhotoCount": "90"
  }];

  $scope.numberOfItems = 3;
  $scope.offSet = 0; //store the offset.
  $scope.addItems = function() {
    if ($scope.offSet <= $scope.Arr.length) //ensure it stops when there are no new elements.
    {
      //adjust the loop based on the offset to retrieve new values
      for (var i = $scope.offSet; i < $scope.offSet + $scope.numberOfItems; i++) {
        $scope.items.push($scope.Arr[i]);
      }
      $scope.offSet += $scope.numberOfItems; //increment the offset by 3.
    }
  };

  $scope.addItems();
});

app.directive('infiniteScroll', [ "$window", function ($window) {
    return {
        link:function (scope, element, attrs) {
            var offset = parseInt(attrs.threshold) || 0;
            var e = element[0];

            element.bind('scroll', function () {
                if (e.scrollTop + e.offsetHeight >= e.scrollHeight - offset) {
                    scope.$apply(attrs.infiniteScroll);
                }
            });
        }
    };
}]);

View the demo here

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

Navigating through a series of items in VueJS can be easily accomplished by using a

Below is the Vue instance I have created: new Vue({ el: '#app', data: { showPerson: true, persons: [ {id: 1, name: 'Alice'}, {id: 2, name: 'Barbara'}, {id: 3, name: &a ...

The creation of the Angular project was unsuccessful due to the outdated circular-json dependency

After attempting to create a new Angular project with the command: ng new hello-world I encountered an error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d6dcc7d6c0d9d4c798dfc6dadbf5859b809b8 ...

Unfolding the potential of variables in JSON.stringify with Node.js

I am currently developing a node.js API for my app, which includes a simple TCP server that accepts NDJSON (newline delimited JSON). However, I have encountered an issue with the JSON stringify method. The problem arises when I attempt to expand all variab ...

In Internet Explorer 8, the PNG image is visible but in IE7, it myster

I have been trying to showcase a logo (PNG created in Paint.NET) on my website (XHTML 1.0 Transitional), using the following code: <body> <div class="header"> <div class="logo"> <img src="logo.png" /> </div> ...

Incorporating a requirement into a function to ensure it is executed only under certain circumstances

I'm currently developing a text-based game using JavaScript that involves picking up a sword with the help of an in-game function. var takeSword = function() { if (currentRoom.hasSword) { $("<p>You picked up a sword.</p&g ...

Creating a Regular Expression that excludes all white spaces, including those at the start or end of the string

I attempted to implement this solution, however, I am encountering some issues: Click here to see the demo <form name="myform1"> Valid? {{ myform1.$valid }} <input type="text" name="username1" ng-model="username1" ng-pattern="/^\S.*?&bso ...

Conversation with form component in angular2

I am currently using ng2-bootstrap-modal. For adding a sample form to the example Confirm Dialog, check out ng2-bootstrap-modal. To change the template: <div class="modal-dialog"> <div class="modal-content"> <form [formGroup]="login ...

Looking to locate or track duplicate values within a multi-dimensional array?

In a multidimensional array, I am looking to detect and count duplicates. If duplicates are found, an alert should be triggered. Arr =[[2,"sk"],[3,"df"],[7,"uz"],[3,"df"],[7,"gh"]] Suggestions: One way to ...

The appearance of the check box remains stagnant visually

Having trouble with dynamically changing the state of a checkbox based on a database value. Even though the value changes after a button click, the visual state of the checkbox remains the same. Here is the link to the JSFiddle for testing: http://jsfiddle ...

What is the best way to showcase images using Vue.js?

For my Vue project, I am encountering issues with the image paths not working properly. Despite trying different variations, such as: <figure class="workout-image"> <img :src= "images.bicep" width= "200px" ...

The ajax keypress event is malfunctioning and the ActionResult parameter is failing to capture any data

I am facing an issue where I want to update the value of a textbox using AJAX on keypress event, but the controller is not receiving any value to perform the calculation (it's receiving null). <script> $('#TotDiscnt').keypress(fu ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...

Tips for removing the current item from a list by clicking on a close icon of the same class name

Is there a way to remove a list item after clicking on its close icon? I am using a JavaScript function to add items to the list. Please refer to the image and code below. Thank you! https://i.stack.imgur.com/aeASd.png The code snippet is as follows: f ...

What methods does Enzyme have for determining the visibility of components?

I am facing an issue with a Checkbox component in my project. I have implemented a simple functionality to hide the checkbox by setting its opacity : 0 based on certain conditions within the containing component (MyCheckbox) MyCheckBox.js import React fr ...

Conceal the rating of WordPress products when they have no ratings

I am looking to remove the star ratings under the title for products with empty reviews. I specifically want to hide the stars without allowing users to leave a new review. I found a similar solution for hiding a different element and attempted to customiz ...

Conceal the information beneath a see-through fixed navigation bar when scrolling downward

the issue: I am facing a challenge with my transparent fixed navbar that has a margin-top gap. The content below the navbar needs to be positioned under it while scrolling down, but the background of the page is a dynamic slideshow of various images. This ...

User-generated JSON Object with Date Information

I have created an API using Node.js/Express that receives input from a form including a date option in the request body. Currently, I am sending dates in the format YYYY-mm-dd, and I have also attempted using dd/mm/YYYY. However, when testing in Postman, ...

Optimal method for identifying all inputs resembling text

I'm in the process of implementing keyboard shortcuts on a webpage, but I seem to be encountering a persistent bug. It is essential that keyboard shortcuts do not get activated while the user is typing in a text-like input field. The approach for hand ...

Preserving objects/variables in non-volatile storage

SUMMARY Though I lack extensive programming experience, I am currently developing a hybrid mobile app with Cordova. The app will contain a substantial amount of static data which needs to be referenced periodically for basic operations. As the volume of o ...

CSS Dilemma: Font Refusing to Change

Hey everyone, I'm new to web development and currently building a basic website on my computer. However, I'm facing an issue where the font I want to use is not changing. Both my HTML and CSS files are located in the correct folder and I am confi ...