The "track by" feature in Angular doesn't seem to be functioning properly when used with an array from $

Within the method of my factory, I am retrieving an array from the server using Angular's $resource:

var resource = $resource("vm", {
    session: function() {
        return Auth.token();
    },
    all: '@all',
    vmId: '@vmId'
}, {
    listVM: {
        method: 'GET',
        url: _baseUrl + 'vm/machines',
        isArray: true,
        cache: false
    }
}

...

_obj.getRunningVMs = function(all) {
    return resource.listVM({all: all}).$promise;
};

...

return _obj;

In my HTML template, I have the following (where the service is named vms in the template):

<div ng-repeat="machine in vms.getRunningVMs(true) track by machine.id">{{machine.owner}} {{machine.host}}</div>

This resulted in an infinite digest error:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations:
[["fn: $watchCollectionWatch; newVal: 22; oldVal: 19"],
["fn: $watchCollectionWatch; newVal: 25; oldVal: 22"],
["fn: $watchCollectionWatch; newVal: 28; oldVal: 25"],
["fn: $watchCollectionWatch; newVal: 31; oldVal: 28"],
["fn: $watchCollectionWatch; newVal: 34; oldVal: 31"]]

This issue arises because each method call returns a new array every time, which fails Angular's equality check for watched collections.

I attempted to use track by:

<div ng-show="managing === 'machines'" ng-repeat="machine in vms.getRunningVMs(true) track by machine.id">{{machine.owner}} {{machine.host}}</div>

However, this led to the following error:

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: machine in vms.getRunningVMs(true) track by machine.id, Duplicate key: undefined, Duplicate value: undefined

Even though id is defined, and the same error occurs when tracking by $index.

Could it be that track by is not designed to handle functions that return new arrays, even with explicit usage? While initially intended to prevent unnecessary DOM manipulation, it seems like there could be a way to make it work in such scenarios.

Answer №1

Referenced from an article on one of my favorite websites:

One key point I recently discovered is:

When utilizing Angular Resources (resource.query(...)), the result is essentially a "future" and not the actual data. Therefore, if ng-repeat is connected to a property in the $scope that represents a future, replacing that future with a new one (such as reloading the data) will cause all items to be destroyed and then recreated, even when using the "track by" feature. My speculation is that this occurs because the future object is initially empty, making it impossible for the track by mechanism to identify any item until it's populated.

To address this issue, I employ the success callback of the resource.query method to update the property in the $scope with the actual returned data.

For instance:

myResource.query({}, function (data) {
    $scope.divisionItems = data;
});

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

Troubleshooting Issue with Formidable Not Working with Multer

Attempting to develop a webpage that enables users to upload a file to a designated folder while specifying a number in an input field. Currently, I am navigating through the Multer library despite typically using body-parser. Referencing both my app.js an ...

Display routes in React using the react-router package

Can I use a console command at runtime to display all routes in my application? Despite utilizing react-router, not all routes seem to be functioning properly. In Rails, you can retrieve a list of routes during runtime. ...

Exploring Javascript's Standard Object: A Guide to Retrieving Two Elements

If I have a special data object: var data = []; data["Name"] = ["Janet", "James", "Jean", "Joe", "John"]; data["Number"] = [25, 22, 37, 19, 40]; Let's say I'm looking for the minimum number value, which is '19' in this case. How ...

The onClick event handler is triggered on page load instead of waiting for a click

Recently delving into React, I encountered an issue while attempting to call a function set as a prop. Take a look at my component below: class SamplesInnerLrg extends Component { playSampleAction(sample,sampleId) { console.log(sample); } ...

Browser freezes unexpectedly every 10-15 minutes

I have an application that displays 10 charts using dygraphs to monitor data. The charts are updated by sending ajax requests to 4 different servlets every 5 seconds. However, after approximately 10-15 minutes, my browser crashes with the "aw! snap" messag ...

When utilizing React router v5, the exact property in a route may not function as expected if there is a

I am attempting to structure routes like Vue.js in an array format: // routes.js export const routing = [ { path: "/setting", component: Setting, }, { path: "/", co ...

How can I show a tooltip in vuetify when a button is disabled?

I am currently using the button and tooltip components in my Vuetify project. I am trying to find a way to only display the tooltip when the button is disabled, but I'm having trouble figuring out how to do it correctly. Right now, the tooltip only a ...

The Google Maps application is having trouble zooming in

I'm having trouble with my function that takes the zoom level and sets the center of the map. When I call setCenter with my positional coordinates and zoom level, the map doesn't zoom in where I want it to. However, the position of my info window ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

The issue of Vue.js template errors within inline code

I am experimenting with using inline-template in combination with vue.js 2.0. This usage is within the context of Laravel blade 5.4: <users inline-template> <tbody> @foreach($users as $user) <tr> ...

Tips for sending a unique button ID to a jQuery click function

Within a table row of a dynamically generated table, I have multiple buttons each with its own functionality. My goal is to figure out how to pass the specific button ID to the onclick event of that table row when one of these buttons is clicked. $(&apos ...

What is the process for connecting an event to the <body> element in backbone.js?

Could it be done? For example, like this: ... interactions { 'click button' : 'performAction' } ... ...

An error has occurred in NodeJS: Value undefined is out of the acceptable range for an unspecified property in the options

I am currently leveraging worker_threads in nodejs to handle the task of reading multiple files and processing the rows for subsequent insertion into a database (using oracle-db). The volume of data I deal with is substantial, typically exceeding one mill ...

What is the reason behind the android code being incompatible with IOS operating systems?

I'm encountering an issue where a particular code is working on Android, but not on IOS. The code in question involves using JavaScript to differentiate the items in a list within an HTML select tag. It's perplexing to me how the code can operat ...

Is there a way to dynamically set a database path in Express.js depending on the user's login status?

I have a backend service that serves as the primary entry point for my web application, where I want to dynamically allocate a database path based on user login. While I understand that this solution may not be scalable in the long run, I plan to use it fo ...

Error: The gulp-cssmin plugin encountered a TypeError because it attempted to read the property '0' of a null

I am attempting to condense my code, but I am encountering this error: D:\gulp-compiler\node_modules\gulp-cssmin\node_modules\clean-css\lib\selectors\extractor.js:66 return name.replace(/^\-\w+\-/, ...

What is the number of steps jQuery animates in?

Exploring my creative side, I decided to create my own custom animate function. Struggling to achieve a seamless animation effect, unlike the smooth transitions produced by jQuery. I'm curious about the formula they utilize to determine the ideal num ...

Use AJAX to send a form submission along with an anchor tag

I've been facing a challenge trying to make this work, but unfortunately, I haven't had any success. Typically, all my forms include a submit input, and I handle AJAX submission in the following manner: <script> $("input#submit").click(fun ...

Adding fewer components to your current Angular 5 project

I have a JS Fiddle showcasing a CSS chart. How can I integrate LESS into my current Angular 5 project to make use of this chart? Also, where should I place the JavaScript and references to the LESS file from this example within my Angular component? The li ...

Function used to update database through AJAX technology

I have implemented a PHP script to update my database using AJAX, and it is working correctly after being tested. To pass the required two variables to the PHP script for updating the database, I created a JavaScript function that utilizes AJAX to call the ...