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

Transferring Variables from WordPress PHP to JavaScript

I have implemented two WordPress plugins - Snippets for PHP code insertion and Scripts n Styles for JavaScript. My objective is to automatically populate a form with the email address of a logged-in user. Here is the PHP snippet used in Snippets: <?p ...

Is it possible to have the cursor rotate or animate by 45 degrees when clicked

Do you know how to create a unique custom cursor using CSS? Say, for example, we have this code: cursor: url(images/cursor.png) 15 15, auto; Now, what if we wanted to take it up a notch and make the cursor rotate -45 degrees when clicked, and then revert ...

Ways to Press the Enter Key on Different Browsers

Looking for a solution to get the keypress action working properly? I have a chat feature where I need to send messages. Here is what I have in the Form-tag (JSP based): function SendMessage() { if (event.keyCode===13) { ale ...

Issue with JQuery UI Tabs not displaying additional HTML pages in JavaScript

One issue I'm facing is that I added Tabs from JQuery UI on my website. The tab containing paragraphs loads fine, but the tabs linked to other HTML pages (which don't have tabs) won't load. Here is my .js file code and .html code: $(funct ...

Clones are made sortable instead of arranging them in a specific order

I have a list that can be sorted with some customizations. However, I am facing an issue where the items in the list get duplicated every time I try to sort them. When I pull one item to sort it, another copy gets added automatically. I am struggling to u ...

Using Angular JS to dynamically load an HTML template from a directive upon clicking a button

When a link is clicked, I am attempting to load an HTML template. A directive has been created with the templateUrl attribute to load the HTML file. Upon clicking the link, a function is called to append a custom directive "myCustomer" to a pre-existing di ...

Using CSS styles in emails can lead to an unexpected horizontal scrolling effect

I am currently working on an application using Symfony, and I have implemented a basic confirmation email with minimal CSS styling. However, the email template is causing horizontal scrolling due to the layout. Below is the HTML code of my email template: ...

Unable to properly test the functionality of the material-ui select component due to an error being thrown stating that the function is not being called

I've been utilizing the material-ui select component in my project and am currently writing tests for it. However, I've encountered an issue regarding testing the onChange event of the component. Here's a snippet of the code for my component ...

Adjust the GTK3 tooltip color exclusively for Eclipse when it is operating on Ubuntu

I am using Eclipse Mars on Ubuntu 15.04 and looking to customize the GTK3 tooltip fg/bg color specifically for Eclipse without impacting other applications. I have come across instructions for changing this color system-wide, but I need guidance on how t ...

Issue with Angular variable not showing desired value

It seems like I'm missing something simple here, but my brain is not cooperating at this late hour. Can someone else take a look and help me out? Here's the HTML snippet in question: <html> <head> <base href="/"> <script sr ...

Manipulate Images Efficiently with jQuery

Are there any jQuery plugins or JavaScript controls available that can display an array of images, with the option to delete an image based on user action? For example, something similar to this: , but with a dedicated delete button on each image. One ad ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

When you use map to transform the value, Observable will consistently return as undefined

Can anyone help me figure out why, when I transform the observable, it returns undefined in the console log even though there are assigned values? HTTP Request getLibraryCardPeople(bookName: String): Observable<people[]> { return this.http.get<Li ...

Change the selection so that only the initial one appears in gray

Is there a way to make the text inside a select field gray out when the first option is selected? Can this be accomplished with just CSS or does it require JS? I have attempted altering the style of the first option, but it only affects the text color in ...

Fixing the error: "React-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a valid function"

Every time I change the option in the selector, I keep encountering this error: "react-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a function" :( import React from "react"; import Product from "./Product" ...

Developing User-Friendly Websites with Responsive Design

While I was working on my project, I realized that using only pixel values in tables and sidebars was a big mistake. This caused issues because if someone had a different screen resolution, my website would look distorted and unappealing. Could you please ...

What is the correct way to utilize "data:" in a jQuery AJAX call?

There seems to be an issue with my code within the deletePost function. The problem lies in the fact that $_GET['title'] is empty. Although I set the title value in the ajax using postTitle: $(this).siblings("h3.blog").text(), it doesn't see ...

Add a fresh item into an array in Json between existing elements

After looping through a JSON object using foreach, the output is as follows: {"Comment": {"id":"1","post_id":"31","created":"14263241"} , "User": {"fname":"Test","lname":"Test2"} } {"Comment": {"id":"2","post_id":"32","created":"14263257"} , "User": {"f ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Ways to position a single item in the middle of a multi-column layout

I need help with aligning dynamic images in a 2-column layout. What's the best way to center a single image or collapse the columns when there's only one image? Currently, the single image is always placed in the left column. Is there a CSS-only ...