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

Hover over the sprites using the "spritely" plugin to see the magic unfold

I'm looking to initiate an animation when the mouse hovers over a sprite and have it stop when the mouse moves away. After exploring various solutions, I found one that seemed promising: Why does jQuery spritely animation play an extra frame on secon ...

Arrange a pair of div containers side by side on the webpage without the need to alter the existing

Is there a way to align these two div side by side? <div class="main_one"> <div class="number_one">Title A</div> </div> <div class="main_two"> <div class="number_two">Title B</div> </div> <div class=" ...

The express js backend (mongodb) is returning {error:{ }}

I'm learning how to POST Data to a Mongo DB using Express.js. Recently, I picked up Express.js for backend server development and this is my app.js const express = require("express"); const mongoose = require("mongoose"); require("dotenv/config") con ...

Tips for successfully importing .eot and .woff documents using Babel?

When attempting to start my project, I encountered the following error message (You may need an appropriate loader to handle this file type.) for .eot, .woff, .ttf, and .svg files: ERROR in ./src/styles/fonts/nm/icons/nm-icons.svg?aaf8685e87a6901c76c52d00 ...

ES6 destructuring in a loop

I attempted to extract the father's name from an array of objects and populate a new array with these names. Here is an example: var people = [ { name: "Mike Smith", family: { father: "Harry Smith", } }, { name: "Tom Jones ...

What is the best way to download a modified canvas with filters using the solutions from stackoverflow?

There have been numerous inquiries regarding how to apply CSS filters to an image, with some solutions that don't utilize CSS filters but still achieve the desired outcome. However, for someone new to JavaScript like myself, these answers can be confu ...

Why is my custom Vuelidate validator not receiving the value from the component where it is being called?

On my registration page, I implemented a custom validator to ensure that the password meets specific criteria such as being at least 12 characters long and containing at least one digit. However, I encountered an issue where the custom validator was not r ...

Customizing Drop Down Button in React Material-UI with Conditions

Trying to figure out how to dynamically populate the second MUI dropdown based on the selection from the first dropdown. Currently, I have both dropdown lists hardcoded. const [queryType, setqueryType] = React.useState(''); const [subCategory, se ...

Error: Client was unable to process JSON data

My server setup looks like this: var http = require('http'); //Defining the port to listen to const PORT=8092; //Function that handles requests and sends responses function handleRequest(request, response){ response.statusCode = 200; ...

Creating a Select component in React without relying on the Material-UI library involves customizing a dropdown

Is there a way to achieve a material UI style Select component without using the material UI library in my project? I'm interested in moving the label to the top left corner when the Select is focused. export default function App({...props}) { retu ...

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

Having trouble parsing the body parameter in Express for a POST request

I am encountering difficulty in accessing the body parameters of a request using Express: const bodyParser = require('body-parser'); const cors = require('cors'); const express = require('express'); const app = express(); con ...

Connect external script actions to HTML elements within components

I'm attempting to incorporate an external script Within public/index.html <script src="https://embed.selly.gg"></script> An event should trigger when I click on a button with specific data attributes. Inside components/shop/ShopItem.js ...

Reset button in AngularJs fails to reset the $error.required message

<div class="form-group"> <input type="text" name="Name" data-ng-model="panNumber" required> <p data-ng-show="loginForm.Name.$error.required && (loginForm.Name.$touched || submitted)" class="error-block">Please make s ...

The LinkedIn API endpoint for accessing client-aware member handles using the query string "handleString" can be found

I am in need of extracting the person ID using the linkedin API https://api.linkedin.com/v2/clientAwareMemberHandles?q=handleString&[email protected] but the response I'm receiving is as follows: { "serviceErrorCode": 100, "messag ...

Mastering React Final Form: Displaying data using a button placed outside the form

I have a query regarding integrating my form component (<InvoiceForm.tsx />) with a button component (<Button.js />) to save its data in the database. The button component is located in another component called <InvoiceList.tsx />, which ...

I'm encountering an issue with the "z-index: -1" property in React

After creating a form placed alongside buttons, I encountered an issue where the form overlaps the buttons and prevents them from being clicked. Despite setting the z-index to -1, it seems that the form remains clickable even when not visible. Research ind ...

Custom container width causes animation to crash when scrolling

I'm having trouble with my header. When the containers change with scrolling, an animation takes place. Everything works fine with native Bootstrap CSS, but when I customize the width of the container in my custom CSS (the width set to 1140px), the an ...

Unexpected appearance of a blue line in Material UI when the overflow attribute is included

For my React application, I've integrated Material-UI along with styled components. The strange thing is that when I use a Chrome browser to view the app, I encounter an issue that doesn't seem to happen in Firefox. The problem arises when I add ...

AngularJS - Bootstrap Datepicker with custom format 'mm-yyyy' still permits users to input date in 'mm-yy' format

After incorporating the bootstrap datepicker into an angular directive and applying it to a textbox, everything appears to be functioning correctly except for the validation aspect. Although I have configured it to only accept dates in 'mm-yyyy' ...