Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this:

{
    "entries": [{
        "id": 2081,
        "name": "BM",
        "niceName": "bodmas"
        }]
    }, {
        "id": 8029,
        "name": "Mas",
        "niceName": "Masm"
        }]
    }],
    "count": 2
}

I'm attempting to loop through this data using the following HTML code:

<option ng-repeat="entry in entries" value="{{entry.name}}">{{entry.name}}</option>

However, running the code results in an error message:

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: entry in entries, Duplicate key: string:c

Here is the snippet of code from my controller:

myApp.controller("MyController", ['$scope', '$http', '$log', function($scope, $http, $log){
       ...

       $http.get('https://myServiceURL').success(function(data){
                    $scope.entries = data;
        });
}]);

I would appreciate any insights on why this error is occurring.

Answer №1

To avoid duplicate keys in your ng-repeat, consider adding track by $index. Instead of:

<option ng-repeat="item in items" value="{{item.name}}">{{item.name}}</option>

Try using:

<option ng-repeat="item in items track by $index" value="{{item.name}}">{{item.name}}</option>

You can find more detailed information in the documentation regarding this error message:

This error occurs when there are duplicate keys in an ngRepeat expression. AngularJS uses keys to link DOM nodes with items, and duplicates are not allowed.

By default, collections are keyed by reference which is suitable for most models but problematic for primitive types that share references.

Answer №2

Your JSON needs to be corrected as follows:

{
    "entries": [{
        "id": 2081,
        "name": "BM",
        "niceName": "bodmas"
    }, {
        "id": 8029,
        "name": "Mas",
        "niceName": "Masm"
    }],
    "count": 2
}

Ensure you are accessing the document at the correct level by using the following code:

$http.get('https://myServiceURL').success(function(data){
    $scope.entries = data.entries;
});

If you follow these steps, everything should work correctly. You can also check out this JSBin for reference.

Answer №3

If there is a need for an additional explanation as to why this situation may arise...

In the case where you are working with a JavaScript object [] or {}

and you plan to pass it into a directive like so

<my-directive my-attribute="{{ myObject }}"></my-directive>

Within the directive, it is imperative to convert myObject back into an object using the following approach

...
controller: function( $scope ){

  $scope.links = $scope.$eval( $scope.myObject );
....

Subsequently, the HTML and ng-repeat functionality will be enabled

...
<span class="" ng-repeat="link in links">
...

ngRepeat does not have the capability to iterate over a single string.

This is how the object appears before $scope.$eval is applied

"[{ hello: 'you' }]"

and post $scope.$eval()

[{ hello: 'you' }] - representing an actual object suitable for iteration.

The error message signifies the inability to repeat over a string. Below is the error I encountered.

Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.0-beta.8/ngRepeat/dupes?p0=link%20in%20links&p1=string%3Al

Answer №4

It appears that the issue lies in how your data is structured within the scope. Your JSON example indicates an object with both an entries property and a count property. However, you are placing the entire object in the scope under the name entries. To access the entries correctly, you would need to reference them as entries.entries, while the count can be accessed through entries.count. The following revised controller code may align more closely with your intended structure:

myApp.controller("MyController", ['$scope', '$http', '$log', function($scope, $http, $log){
    ...

    $http.get('https://myServiceURL').success(function(data){
        $scope.entries = data.entries;
        $scope.count = data.count;
    });
}]);

Answer №5

// If you wish for this Web Service to be accessible from script by using ASP.NET AJAX, simply remove the comments in the line below.

[System.Web.Script.Services.ScriptService] ==> Remove comments in this line when utilizing .NET Service

Answer №6

In ng-repeat, duplicates are not allowed. Here is an example:

    <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="angular.js"></script>

</head>
<body>
    <div ng-app="myApp" ng-controller="personController">
        <table>
            <tr> <th>First Name</th> <th>Last Name</th> </tr>
            <tr ng-repeat="person in people track by $index">
                <td>{{person.firstName}}</td>
                <td>{{person.lastName}}</td>
                <td><input type="button" value="Select" ng-click="showDetails($index)" /></td>
            </tr>

        </table> <hr />
        <table>
            <tr ng-repeat="person1 in items track by $index">
                <td>{{person1.firstName}}</td>
                <td>{{person1.lastName}}</td>
            </tr>
        </table>
        <span>   {{sayHello()}}</span>
    </div>
    <script> var myApp = angular.module("myApp", []);
        myApp.controller("personController", ['$scope', function ($scope)
        { 
            $scope.people = [{ firstName: "F1", lastName: "L1" },
                { firstName: "F2", lastName: "L2" }, 
                { firstName: "F3", lastName: "L3" }, 
                { firstName: "F4", lastName: "L4" }, 
                { firstName: "F5", lastName: "L5" }]
            $scope.items = [];
            $scope.selectedPerson = $scope.people[0];
            $scope.showDetails = function (ind) 
            { 
                $scope.selectedPerson = $scope.people[ind];
                $scope.items.push($scope.selectedPerson);
            }
            $scope.sayHello = function ()
            {
                return $scope.items.firstName;
            }
        }]) </script>
</body>
</html>

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

Guide on sending PHP array to jQuery using AJAX with JSON?

Currently, I am working on building a calculator that utilizes ajax in jQuery to send values to a PHP file and then receive the results back in jQuery. While I have accomplished getting one result returned successfully, my goal is to have two separate resu ...

Confirming delete with jQuery and AJAX

Before sending an AJAX request to remove an item from the database, I require an OK/Cancel delete confirmation dialog box. var id=ID; $.ajax({ type: "POST", url: "sample.aspx?Mode=Delete", data: { id: id }, success: function (response) ...

Build a Node.js application with Express to host static files

I am attempting to provide my static files "web.html" and "mobile.html", but I want them to be served only if the user is accessing from a web or mobile device. After some research, I came up with this code: var express = require('express'); va ...

Vue.js: crafting a universal composable is proving challenging

I am faced with the challenge of making a universal composable. In my scenario, I have 3 components - ItemSwiper, ItemCard, and ViewRecipeDetail. ItemSwiper contains card slides and serves as the parent of ItemCard. The loop of recipes in ItemSwiper loo ...

Sorting through an array using a different array of values

Looking to filter one array with another, where values in the first array should match 'id' in the second array for filtering. The arrays in question are: const array1 = [a, b, c, d] The array to be filtered based on matching 'id' va ...

Is Threading Suitable for a For Loop in Python?

Hello everyone, I am new to this platform and would like to seek help with a coding issue that I am facing. I have a for loop that I want to execute using threading. Here's an example: for i in range(0,100): print(i) I want to use 4-5 threads ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

What could be the reason for the error message when using rs.send with a string input?

I'm a beginner in node and express, and I was trying to create an HTML form that takes two numbers and displays the result using "express" and "node". However, when I use rs.send(result), I encounter the following error: https://i.sstatic.net/FcUNJ.p ...

Connects URLs to the displayed outcomes in jQuery Auto-suggest Interface

This particular code snippet has been modified from a tutorial on jQuery autocomplete <!doctype html> <html lang="en> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Nested arrays in the JavaScript programming language

Is this JavaScript code accurate: var options = []; options.push(["Tom","Smith"]); options.push(["Mary","Jones"]); where each item in options is a two-element array of strings. I plan to add items to options using a for loop. Furthermore, can I i ...

fetching numerous JSON documents using jquery

I am struggling to retrieve data from multiple JSON files and display it in a table. Despite being successful in appending data from one JSON file, I encountered issues when trying to pull data from multiple files. Here is my code: var uri = 'sharepo ...

What causes a ReactJS component to disappear upon page refresh?

After the user clicks the Login button in the Instructor Login Form, I want to display the Instructor Profile component. Everything functions properly until I refresh the page, at which point the User Profile component disappears. Here is a screenshot of ...

Firestore javascript query is returning empty results

Yesterday everything was working smoothly, but this morning it suddenly stopped moving forward. The Firestore query is not returning anything - no errors, no response. Surprisingly, the console displays the phone perfectly fine. Additionally, the phone n ...

Disappear text gradually while scrolling horizontally

There is a need to create a special block that displays fading text on horizontal scroll. However, the problem is that the block is situated on a non-uniform background, making the usual solution of adding a linear gradient on the sides unsuitable. Click ...

How to use AJAX script to call a non-static page method in ASP.NET

Is it possible to achieve this task without utilizing the UpdatePanel feature? ...

Day Change Triggers React [Native] View Update

I've been working on a React Native component that needs to update itself when the day changes, regardless of user interaction. Is there another method besides using setInterval for this task? If I use setTimeout in my viewDidLoad function with the n ...

Is iterating through object with a hasOwnProperty validation necessary?

Is there any benefit to using hasOwnProperty in a loop when an object will always have properties? Take this scenario: const fruits = { banana: 15, kiwi: 10, pineapple: 6, } for (let key in fruits) { if (fruits.hasOwnProperty(key)) { ...

Attempting to verify JavaScript input by utilizing OnClick and a custom function. Regardless of the content inputted, the system consistently confirms that the format is accurate

I am currently working on a project that involves an HTML file and an external JavaScript file. In the HTML file, there is user input and a validation button that triggers the courseValidation() function when clicked. However, I am facing an issue with the ...

Why are the radio buttons not aligned with the text in the center?

Currently, I am in the process of building a form that includes radio buttons. However, I've encountered an issue where the text next to the radio buttons appears on a different level than the buttons themselves. How can I go about fixing this partic ...

Where is the appname saved in the Yeoman Angular generator?

After utilizing yeoman to create a project, I discovered that I mistakenly included the word "app" at the end of the name during creation. Now, all new elements within this project have two instances of "app" at the end, such as angular.module('myProj ...