Attempting to showcase segments of an array one by one

Currently, I am showcasing the contents of an array on a view using $scope.array.

The array's content is loaded through a request to my server. However, exhibiting every element at once in the view is taking too long because $scope.array has a large number of elements.

To improve the user experience, I want to display the array part by part. Initially, I thought that simply adding data chunk by chunk to $scope.array would work, but it did not.

I realized that the current $digest loop would only complete when my array was full. I attempted using the Async library to add chunks asynchronously to $scope in hopes of bypassing the $digest issue, but it was unsuccessful.

Now, I am struggling to find a solution for properly displaying the data. If you have any insights or experiences with similar issues, I would greatly appreciate hearing about them!

Thank you very much.

Answer №1

If you want to avoid pagination and periodic requests, consider organizing all your data in one array that is not directly linked to the user interface. Then, periodically transfer chunks of this data into a second array that is connected to the UI. This approach allows for smoother $digest cycles and page rendering.

Here's a simple example:

<table>
  <tr ng-repeat="item in shownItems track by $index">
    <td>{{item}}</td>
  </tr>
</table>

In the controller:

app.controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {
  // Array bound to UI
  $scope.shownItems = [];
  // Backing data
  var fullItemsList = [];
  // Generating fake data (replace with actual server fetch)
  for(var ii = 0; ii < 50000; ii++){
    fullItemsList.push("AYYYLMAO "  + ii);
  }

  // Chunk size for transferring items
  var chunkSize = 500;
  var currentChunkIndex = 0;

  // Transfer chunk of items to UI-bound array 
  function addMoreItems(){
    var start = currentChunkIndex * chunkSize;
    var end = (currentChunkIndex + 1) * chunkSize;
    for(var ii = start; ii < end; ii++){
      if(!fullItemsList[ii]){
        break;
      }
      $scope.shownItems.push(fullItemsList[ii]);
    }
    currentChunkIndex++;
  }

  // Periodic addition of items using timeouts
  function periodicAdd(){
    $timeout(function(){
      addMoreItems();
      if(currentChunkIndex*chunkSize >= $scope.shownItems.length){
        periodicAdd();
      }
    }, 0);
  }
  
  // Add initial chunk immediately
  addMoreItems();
  // Start periodic adding
  periodicAdd();
}]);

Click here for an example on Plunker

Please note that this example is basic. The initial load of 50k rows runs on the UI thread, which may differ from an asynchronous data fetch from a server. Ensure to initiate the periodic adding only after data retrieval completes. Adjust the timeout duration to maintain app performance. Remember to handle timeouts properly.

Answer №2

Consider implementing server-side pagination for better performance. Sometimes using one-time bindings may not be sufficient, especially when dealing with complex template logic that involves showing/hiding parts based on data properties and requires editing.

If you need to filter your array based on specific criteria (such as month and year), it's recommended to handle this on the backend and send the criteria to the server:

GET /my_data?year=2019&month=10&page=2
.

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

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Using JavaScript to escape a single quote within a property value of a JavaScript object

I am currently facing the challenge of dynamically splitting a JavaScript Object into HTML markup from C#.NET code behind. Once I retrieve the data, I format it into a string and create an object within that string to be displayed in the HTML markup. var ...

Redirecting in AngularJS using ui-router post login authentication

I have been working on a project that utilizes AngularJS with ui-router. Everything is functioning properly except for the redirect from the login screen to the preview state upon the initial load. The default state is set to home - For instance, if a us ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

collaborating with numerous JavaScripts

I am currently working on a project that involves several JavaScript functionalities such as an image viewer, carousel, and toggles. Now, I need to implement a pop-up form, but when I add the JavaScript for the pop-up, the entire page stops working. I wou ...

Exploring the application of Javascript in Java Selenium Webdriver

I'm having trouble performing a click operation on a button using JavaScript in Selenium Webdriver. Here is my JavaScipt code: JavascriptExecutor js=(JavascriptExecutor) driver; // js.executeScript("document.getElementById('custo ...

Display the translated text to the user while storing a different value in the database using AngularJS and Angular-Translate

Currently utilizing AngularJS and attempting to utilize $translate for translations. I am facing an issue with a dropdown list where I display translated options for the user. For instance, in English = "Red" and in French = "Rouge", etc. The problem ar ...

Using Vue.js to iterate through a nested array from an object key

This is a complex v-for loop nested inside another v-for. It displays a list of questions along with the corresponding answers for each question. The key for the question will be used as the key for grouped_answers. The structure of the v-for loop is show ...

When using Express.js for file uploading, it is important to first verify that a file has been sent, set a maximum file size limit, and ensure

After working with expressjs for a month, I've encountered some issues with file uploads. Despite researching on Google and various blogs, I haven't been able to find answers to the following three questions: What do I need to do or what setting ...

What is the purpose of requiring the explicit invocation of app.listen(port) to enable express-ws to function properly?

I've recently started exploring NodeJS Express and came across the official tutorial from express-ws for setting up websockets in a simple project generated using npx express-generator. While following the tutorial, I noticed that in the app.js file, ...

Attach a Material-UI Popper component to a customized edge label in a React Flow

After finding inspiration from this particular example in the react-flow documentation, I decided to create my own customized version. It showcases a Material Ui Popper that appears when the edge is selected. However, my problem arises when attempting to z ...

$injector encountered a problem resolving the required dependency

Currently, I am attempting to adopt the LIFT protocol (Locate, Identify, Flat, Try(Dry)) for organizing my Angular projects. However, I am encountering difficulties in handling dependencies from other files. Here is the factory I have: (function () { ...

When iterating through a loop, the final value in an array is often overlooked

I have been attempting to iterate through an array to determine if any of the values, when compared to all other values in the array using the modulo operation, do not return a 0. Essentially, this process should only return the prime numbers in the array ...

using node.js to save query results as global variables

Help needed! I'm struggling to pass the results of my query statement to a global variable in order to dynamically configure my jsganntimproved chart. Any suggestions on what could be going wrong? In the snippet below, the console.log(taskItem) retur ...

What are the techniques for implementing an if statement in CSS or resolving it through JavaScript?

Demo available at the bottom of the page Within my code, there is a div called #myDiv that defaults to an opacity of 0. Upon hovering over #myDiv, the opacity changes to 1. See the CSS snippet below: #myDiv { opacity: 0; } #myDiv:hover { opacity: 1 ...

I am facing issues with running my project due to a gyp error. Can anyone provide guidance on resolving this problem?

Every time I execute my code, I encounter the same persistent error. Despite attempting to resolve it by uninstalling and reinstalling Node and npm, the issue persists. Furthermore, the lack of "node_modules" exacerbates the problem. How can I rectify this ...

Utilize SWR to retrieve data that corresponds to the chosen value from the dropdown menu

Can SWR fetch data based on the selected value in a dropdown? Initially, it works, but when I select a previously selected value, it doesn't fetch the correct data. Using the Fetch API const { data: entities } = useSWR( currentEntity?.enti ...

Guide to importing a JSON file?

Is there a way to access JSON data from a separate file? I attempted: obdatabase.json { "pobject" :[ { "pname":"Pikachu" , "pid":"1" }, { "pname":"squirtle" , "pid":"2" }, { "pname":"Justinbieber" , "pid":"3" } ]}; test.php <script src= ...

Why does the <div> element still have an offset even though its width and height are set to 100px and padding, margin, and border are set to 0px?

After styling my div element with specific CSS rules, I'm encountering an issue. The div has a set width and height of 100px along with padding, border, and margin all set to 0px. However, the elements are not being offset from the edges of the browse ...

Can a variable containing HTML code be iterated through with a loop?

I am currently working on setting up a select button that will receive options from an ajax call. The ajax call is functioning properly. However, I am facing a challenge when trying to create a variable containing the HTML. I am unsure of how to iterate a ...