Tips for utilizing ng-repeat with a function that generates a fresh object?

My HTML code includes the following element:

<button ng-click="console.log(key)" ng-repeat="(key, value) in getLocalStorageKeys() track by $index">

In my JavaScript file, I have the following function:

$scope.getLocalStorageKeys = function(){
    return localStorageService.get('accountKeys');
};

You can view the Local Storage value here:

Despite my efforts, I continue to encounter the following error message:

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached.
Aborting!
Watchers fired in the last 5 iterations: [["fn: $watchCollectionWatch; newVal: 121; oldVal: 118"],["fn: $watchCollectionWatch; newVal: 124; oldVal: 121"],["fn: $watchCollectionWatch; newVal: 127; oldVal: 124"],["fn: $watchCollectionWatch; newVal: 130; oldVal: 127"],["fn: $watchCollectionWatch; newVal: 133; oldVal: 130"]]

I understand that ng-repeat attempts to match exact objects and that getLocalStorageKeys creates a new object each time it is called. However, I am puzzled as to why adding "track by $index" does not resolve this issue, as my understanding was that "track by" was designed to address this specific problem. What could be causing this error?

Answer №1

To begin, you can start by converting your object into an array; for example:

var arr = [];
var obj = localStorageService.get('accountKeys');
for (var i in obj) {
  var item = obj[i];
  item.id = i;
  arr.push(item);
}

Next, you can use ng-repeat to iterate over this array, while ensuring that each element is tracked using a unique identifier (such as the id key, which holds the email addresses)

<button ng-click="console.log(key)" ng-repeat="item in getLsKeys() track by item.id">

Remember: it's more efficient to perform the object to array conversion outside of the getLsKeys function if possible. This way, it doesn't need to be done repeatedly during every digest cycle.

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

Color picker can be utilized as an HTML input element by following these steps

After trying out various color pickers, I was not satisfied with their performance until I stumbled upon Spectrum - The No Hassle jQuery Colorpicker. It perfectly met my requirements. <html> <head> <meta http-equiv="content-type" content="t ...

Understanding the extent of variables in Javascript

I'm struggling to comprehend the scope of 'this' in this particular situation. I can easily call each of these functions like: this.startTracking(); from within the time tracker switch object. However, when attempting to execute the code: Dr ...

The generation of the npm bin script is not working as expected on Windows operating systems

I'm working on developing an NPM package for command line use. I've set up npm's bin in my package.json to specify the JS file to be executed. Here is a snippet from my package.json: "name": "textree", "bin": { "textree": "./src/cli.js" ...

Can you please explain how to indicate a modification in a JSON object with Polymer, transferring information from Javascript, and subsequently displaying child elements?

Currently, I am creating a JSON file that contains a random assortment of X's and O's. My goal is to display these elements in a grid format using a custom Polymer element. Initially, everything works fine as I can see a new grid generated each t ...

Avoiding repetition in json array using reactjs with the help of axios

After receiving guidance from @Akrion, I managed to resolve the issue! Check out my comments below our conversation for the solution. I am relatively new to reactJS and axios, but I recently collaborated with a classmate on a project. Now, I find myself s ...

Issue encountered in performing a post request using AngularJS

One of the functions in my code is a post call: save2 : function ( lotto ) { var configDistintaIngrediente = { params: { distintaBaseGelato_id: 1, ingrediente_id: 2, quantit ...

Why is my PanResponder failing to detect changes in the updated state?

This is the code snippet I'm currently working on: const processPinch = (x1: number, y1: number, x2: number, y2: number) => { function calcDistance(x1: number, y1: number, x2: number, y2: number) { const dx = x1 - x2; const dy = y1 ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

Exploring the contrast between window and document within jQuery

I'm curious about the distinction between document and window in jQuery. These two are commonly utilized, but I haven't quite grasped their differences. ...

What advantages and disadvantages come with using timeouts versus using countdowns in conjunction with an asynchronous content loading call in JavaScript/jQuery?

It seems to me that I may be overcomplicating things with the recursive approach. Wait for 2 seconds before loading the first set of modules: function loadFirstSet() { $('[data-content]:not(.loaded)').each( function() { $(this).load($(thi ...

Steps to begin again an Ionic application on IOS operating system

Currently, I am in the process of developing an Ionic application for both Android and IOS platforms. One challenge I am facing is that if any errors occur either on the server side or client side, the app automatically restarts. For Android, I have succe ...

Execute function upon initial user interaction (click for desktop users / tap for mobile users) with the Document Object Model (DOM)

Looking to trigger a function only on the initial interaction with the DOM. Are there any vanilla JavaScript options available? I've brainstormed this approach. Is it on track? window.addEventListener("click", function onFirstTouch() { console.l ...

Trouble with X-editable: Unable to view values when editing and setting values using J

When using X-editable to modify a form with data, I encounter an issue. Initially, the values are loaded from the database to the HTML, but when users try to edit by clicking on the "Edit" button, all values appear as "Empty" instead of their actual cont ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

How to make Angular 5 wait for promises to finish executing in a for loop

My task involves working with an array like this: arr = ['res1', 'res2', 'res3']; For each value in the arr, I need to make an API call that returns a promise. arr.forEach(val => this.getPromise(val)); The getPromise me ...

Creating an If statement to evaluate the state of a parameter

In my simple Graphics User Interface, when the user clicks on "move", a yellow rectangle div moves across the screen. Now, I am trying to implement an event based on the position of the rectangle on the page. For example, if the div is at 400px (right), t ...

When the button is clicked, my goal is to increase the value of the text field by one using JavaScript

I need the functionality for each button to increment the value text field located next to it <input type="number" value="0" min="0" max="5" step="1" id="qty"/> <button onclick="buttonClick()" type="button" class="btn btn-success btn-sm" id="add" ...

What is the process for configuring SSL in node.js and express.js?

I'm currently working on setting up my application to run in HTTPS mode. Despite thinking that my configuration is correct, the page isn't loading at all. Within my SSL folder, I have the following files: credentials.js my-ca.pem my-cert.pem my ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

How can one use C# and Selenium to send text to a hidden textarea with the attribute style="display: none;"?

I'm encountering an issue where I am unable to write in the textarea using the sendkeys function in Selenium. The specific textarea I am trying to target has an ID of 'txtSkillsTaught-Value' and is located after a script tag that seems to be ...