How does ng-repeat determine the presence of duplicates within an array of objects?

angular.module("myApp",[])
       .controller("myCtrl",function($scope) {
         $scope.persons = [{name:"teja",age:11},
                           {name:"Ash",age:12},
                           {name:"teja",age:11}];
                           });

In the realm of Angular, the presence of duplicate elements within an array declared in ng-repeat is normally not allowed. However, there exists a solution by employing "track by $index" which can accommodate duplicates within the array. This begs the question: How does ng-repeat discern the existence of duplicates within the array? What criteria does it rely on to make this determination? It's worth noting that when a new object is created, a new reference for that object is also generated. Yet in the provided code snippet, how does ng-repeat manage to pinpoint the duplicates.

<div ng-repeat="person in  persons">
{{ person.name }}
</div>

Answer №1

According to the information provided in the documentation

In order to reduce the creation of DOM elements, ngRepeat employs a function to efficiently manage all items within the collection along with their associated DOM elements. This means that if an item is added to the collection, ngRepeat will recognize that existing items already have corresponding DOM elements and avoid unnecessary re-rendering.

The default tracking function (which identifies items based on their identity) prohibits the presence of duplicate items within arrays. This restriction exists because duplicates would disrupt the one-to-one mapping between collection items and DOM elements.

Hence, if you happen to have two identical elements (meaning that angular.equals(a, b)), Angular will not be able to properly manage the relationship between DOM elements and items, resulting in an error being generated.

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

What is the process for establishing a connection between two sets of data?

I am working with two mongoose models: user.js and note.js, which correspond to the collections notes and users. I want users to be able to save their notes, but I'm unsure how to create relationships between these collections. Ideally, I would like t ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...

A specialized HTTP interceptor designed for individual APIs

Hey there, I am currently working with 3 different APIs that require unique auth tokens for authentication. My goal is to set up 3 separate HTTP interceptors, one for each API. While I'm familiar with creating a generic httpInterceptor for the entire ...

How to pass an axios-retrieved array prop to a child component in a Laravel Vue SPA?

How can a Laravel Vue SPA pass an array prop retrieved by axios to a child component? The json object from somedomain.com/channellist is fetched using axios and needs to be passed to the child component. What's the best way to ensure that activeChan ...

Does JSON have a special reserved key for identifying the time?

I've noticed an interesting issue when logging the json string of a key labeled tid - it always shows up as 0. Take a look at this example: var transaction = {tid:1, type:0, time:126312736}; var transStr = JSON.stringify(transaction); console.log(tra ...

Instructions for displaying the opening window form when offline in a hybrid mobile app

Embarking on hybrid mobile app development is a new journey for me. Typically, I use ionic, cordova, and angular.js for the frontend of my mobile applications, paired with .net for the backend. Here's the scenario I aim to execute: In my mobile app, ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

JS Executing functions in a pop-up window

Recently, I have been immersing myself in learning JS and experimenting with webpage interactions. It started with scraping data, but now I am also venturing into performing actions on specific webpages. For example, there is a webpage that features a butt ...

Utilizing jQuery to target elements that are dynamically generated upon successful AJAX response

When handling dynamically created elements on ajax success, I encountered an issue. I have multiple checkboxes within a table and when the table content is replaced on ajax success, I am unable to select any new checkbox. While it is possible to trigger cl ...

Add a new component to a Vue.js instance that is already in use

Just getting started with Vue.js I'm looking to register a local component following the instructions here: https://v2.vuejs.org/v2/guide/components.html#Local-Registration The catch is that I need to register the component to an existing Vue insta ...

Using JSON in Highcharts: Customizing Border and Label Colors

Currently using Highcharts in JSON format with the following syntax: var neutral_color = '#c4c4c4', medium_grey = '#929292'; lineChartJSON['chart']['plotBorderColor'] = medium_grey; lineChartJSON['chart&ap ...

Move the cursor to the start of a textarea with the power of jQuery

MyEvent.prototype.sendMessage_ = function(input) { //input is this.find('#mytextarea'); if (input.val().trim() != '') { input.val(''); $('#mytextarea').focus(); } }; //...within the html....// <text ...

Execute a join operation on a dataset solely based on the matching of substrings

Looking to perform a join on a collection where student names match and the last string after the "_" in the log column's value matches the id variable. The challenge lies in matching a substring of a string within the logs column. One way to achieve ...

Interactive elements embedded within an image - digital board game

I'm currently working on integrating a board game into React, and I am facing some difficulties in figuring out how to translate the board squares shown in the image into data. Is there a method through which I can assign unique IDs to each square di ...

How to access a variable in an Angular Factory's callback function from outside the factory

Here's a look at the structure of My Factory: .factory('MyFactory', function(){ return: { someFunction: functon(firstParam, secondParam, resultObject) { $http.get(url).success(resultObject); } ...

What is the best way to ensure bidirectional text appears correctly when two conflicting languages are combined, ensuring explicit directionality is set?

As I work on localization implementation, I encounter an issue with the directionality of mixed characters on the page. The text content is stored in a json file and inserted into the DOM using a Vue.js template. While individual characters display corre ...

Unable to retrieve this object because of a intricate JavaScript function in Vue.js

For my VueJs project, I am utilizing the popular vue-select component. I wanted to customize a keyDownEvent and consulted the documentation for guidance. However, I found the example provided using a mix of modern JS techniques to be quite cryptic. <tem ...

Ways to get to the bottom in a React component using a button

I've been struggling to automatically scroll the user to the bottom of the page when they click on a button. Despite my best efforts, I haven't been able to find a solution. Can someone please assist me in achieving this goal? Thank you ...

Error occurred due to an improperly formatted authorization header while attempting to upload an object to S3 using the JavaScript SDK

When attempting to upload an object to Amazon S3 using their JavaScript SDK, I encounter the following error message: <Error> <Code>AuthorizationHeaderMalformed</Code> <Message>The authorization header is malformed; the reg ...