AngularJS - "Refrain from replicating items in a repeater"

I am facing an issue with creating HTML textarea elements for each member of an array. Despite consulting the AngularJS documentation and attempting different track by expressions, I am unable to render them.

The problem arises when a user inputs the same text in multiple textareas. It appears that Angular is treating the textarea value as a unique key. One potential solution could be to append or remove an arbitrary identifier before the text, although this seems like a workaround.

To clarify, the textareas are displayed properly until the user submits the form (using JavaScript only - no server round-trip), after which subsequent code processes and displays the input.

Thank you in advance.

The specific error message received is:

Duplicates in a repeater are not allowed. 
Use 'track by' expression to specify unique keys. 
Repeater: openEndedQuestion in openEndedQuestions track by openEndedQuestion.id, 
Duplicate key: undefined

The provided HTML code is:

<tr ng-repeat="openEndedQuestion in openEndedQuestions">
    <td width="375" style="font-size: 18px;">
        <b>{{openEndedQuestion}}</b><br>
        <textarea id="openEndedAnswer_{{$index}}" cols="80"></textarea>
    </td>
</tr>

The next stage of HTML code is:

<tr ng-repeat="openEndedAnswer in openEndedAnswers">
    <td width="375" style="font-size: 18px;">
        <b>{{openEndedAnswer}}</b>
    </td>

    <td width="225">
        <span style="font-size: 35px; padding: 2px; color: #468847;" 
              ng-repeat="starIndex in [0, 1, 2, 3, 4]"
              ng-click="povStarTracker.setStarRating($parent.$index, starIndex + 1)" 
              ng-class="povStarTracker.getClassForStar($parent.$index, starIndex)"></span>
    </td>
</tr>

The JSON data behind this issue is:

"openEndedQuestions" : [ 
    "Do you think the coach is being fair?", 
    "Should the coach give all of his players a chance to play in the games?", 
    "Should Austin say anything about this to his coach?", 
    "What could Ryan say to Austin?"
]

Answer №1

Include the track by section in your ng-repeat code

You can either use by $index or by openEndedQuestion

 <tr ng-repeat="oeq in openEndedQuestions track by oeq">

or

 <tr ng-repeat="oeq in openEndedQuestions track by $index">

The second option is preferred

It's also recommended to avoid binding to primitives like strings and numbers in Angular. Consider this alternative approach:

In the controller:

$scope.questions = [

 {id:1, text: "Are you enjoying the new content?"}, 
 {id:2, text: "What do you think of the latest updates?"}, 
 {id:3, text: "Should suggestions from users be implemented?"}, 
 {id:4, text: "How can we improve user experience?"}
]

And in the template:

 <tr ng-repeat="q in questions track by q.id">

Check out the example on jsfiddle: http://jsfiddle.net/yourusername/example123/

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

transform constant values into API requests using React

The sample dataset mentioned will be retrieved from a backend API call handled by Flask. The API has already been configured on the backend. const rows = [ { name: "XYZ", age: "12", email: "<a href="/cdn-cgi/l/emai ...

What is the best way to change a JSON string into an array of mysterious objects?

I am currently working on a flashcard generator project and I am dealing with a JSON String that is quite complex. The JSON String contains multiple arrays and objects structured like this: data = [{"front":"What is your name?","back":"Billy"},{"front":"H ...

Tips for retrieving the file name from the <input type="file" tag within a JSP page

I am looking to retrieve the file path from an HTML input type="file, which is selected by the user in the file dialog. <script> function OpenFileDialog(form) { var a = document.getElementById("inputfile").click(); SampleF ...

The issue of Jquery selectors not functioning properly when used with variables

Currently working on a script in the console that aims to extract and display the user's chat nickname. Initially, we will attempt to achieve this by copying and pasting paths: We inspect the user's name in the Chrome console and copy its selec ...

I am looking to modify the file name in the save as dialog box whenever the user performs a right-click

In my current project, I am utilizing PHP along with javascript/jQuery. I have a specific requirement where I need to alter the filename displayed in the save as dialog when a user right-clicks on an image and chooses to save it. For instance, I wish to ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Is there a way to prevent users from selecting dates and times prior to today, as well as blocking out the hours of 9:00am

Users are required to select a date within the range of today's date and one month in the future, and a time between 9:00am and 9:00pm. How can I implement validation to ensure this? <div class="row"> <div class="col"> <label cl ...

How to locate the cell with a specific class using JavaScript/jQuery

I need help with the following code snippet: var output = '<tr>'+ '<td class="class1">One</td>'+ '<td class="selected">Two</td>'+ '<td>< ...

Retrieving the date input value in AngularJS using ng-model

Attempting to retrieve the value of my HTML 5 input date component by using ng-model binding as shown below: <input type="date" id="dateFin" class="form-control" name="dateFin" ng-model="filtres.dateFin" placeholder="dd/MM/yyyy" min="01 ...

Capture video frames from a webcam using HTML and implement them in OPENCV with Python

While many may find it simple, I am facing a challenge in extracting video frames from HTML or JavaScript and utilizing them in my Python OPENCV project. I have a strong background in Python OPENCV and Deeplearning, but lack knowledge in HTML and JavaScr ...

Dealing with numerous Ajax calls within a single Ajax request

I am utilizing the $http method in angularjs to retrieve multiple "parent" elements. Within the success method of these Ajax calls, I need to loop through the parent elements and make another Ajax call for each parent element to fetch its corresponding chi ...

Enhance each category changing with jQuery page transitions

Is there a way to add page transitions based on category names and quantities in PHP? For example, when clicking on the "office" category, can a popup overlay be displayed with the category name and quantity while the content loads? The focus is on creat ...

Could there be a mistake in the way array combinatorics are implemented in JavaScript?

Having encountered the necessity for generating unique combinations when dealing with multiple arrays, I developed this script. While it functions as intended during the combination process, storing the result in a final array yields unexpected outcomes. ...

Disregard the instructions upon loading the page

I've implemented a directive to automatically focus on the newest input field added to my page. It works well, but there is one issue - when the page loads, the last input is selected by default. I want to exclude this behavior during page load and in ...

Prevent the duplication of objects within the current Angular model

Exploring the process of merging two arrays with some common occurrences in each array, I attempted the following: var json_dest = [ { "legID":"12121", "message":212112 }, { "legID":"12122", "message":212112 ...

Navigating through cors in next.js

Currently, I have set up my front end using Netlify and my backend using Heroku with Next.js For the fetch request on the front end, here is an example: fetch(`https://backendname.herokuapp.com/data`, { method: 'POST', headers: { & ...

Why don't I need to include an onload event to execute the setInterval() method within the script tag?

Hey there! I'm diving into the world of Javascript and I've come across this interesting code that changes an image every four seconds. Surprisingly, it's working perfectly fine even though I didn't include an onload event to execute th ...

Discovering the method for retrieving JavaScript output in Selenium

Whenever I need to run JavaScript code, the following script has been proven to work effectively: from selenium import webdriver driver=webdriver.Firefox() driver.get("https:example.com") driver.execute_script('isLogin()') However, when I atte ...

"Encountered an issue while serializing the user for session storage in Passport.js. Have you already implemented code for

I have recently started learning nodejs and I am currently working on creating a login system. I followed the code for serializing the user from the passport documentation and placed it in config/passport.js. However, I keep encountering the error "Failed ...

FlexNav excluding

I have implemented FlexNav for my website navigation. The demo I used sets the width of top-level menu items to 20%, which works well with five menu items. .flexnav li { . . . width: 20%; } However, in my menu, the text lengths of the top ...