Displaying error messages on a form that uses ng-repeat in Angular

I am trying to dynamically generate input fields using ng repeat in Angular, but I am encountering an issue where error messages only appear on the last element. How can I make these error messages apply to each individual element?

<form name="setPlayersForm">
  <div ng-repeat="player in rp.KillerService.getPlayers() track by $index" class="name-input">
    <input type="text"
           placeholder="Your Name"
           ng-model="player.name"
           required/>
    <a class="fa fa-trash-o" ng-if="player.newPlayer" ng-click="rp.removePlayer(player)"></a>
  </div>
  <ng-messages for="setPlayersForm.$error" ng-if="rp.submitted">
    <ng-message when="required" class="alert-box alert">This field is required</ng-message>
  </ng-messages>
</form>

Answer №1

When working with inputs in ng-repeat, I typically use this method. Check out the example code below:

<form name="sampleForm" novalidate>
    <div ng-repeat="item in items">
        <input type="text" name="name{{$index}}" required ng-model="item.name">
        <div ng-messages="sampleForm['name'+$index].$error">
            <div ng-message="required" class="error">This field is required</div>
        </div>

        <input type="text" name="price{{$index}}" required ng-model="item.price">
        <div ng-messages="sampleForm['price'+$index].$error">
            <div ng-message="required" class="error">This field is required</div>
        </div>
    </div>
</form>

If you have any questions or need clarification, feel free to leave a comment.

Answer №2

The ngMessage functions like a switch case where the correct group needs to be passed to identify errors. In Angular, when creating a form, it is wrapped by the form's name and the names of its inputs, as shown below:

<form name="myForm">
  <input name="myInput">
  <input name="myInput2">
  <input name="myInput3">
</form>

Wrap it similar to this structure with respective $error for each input:

myform = {
 myInput: {
  $error:{
   //...
  }
 },
 myInput2: {
   //...
 },
 myInput3:{
   //...
 },
   //...
}

The form name should be used and not just contain the actual error of each element (should include an array with relevant data of each error). The input names must be utilized as seen in the plunkr example:

http://plnkr.co/edit/I43HTQeWZS85N55hXGfF?p=preview

HTML:

<form name="setPlayersForm">
  <div ng-repeat="player in players track by $index" class="name-input">
    <div ng-init="player.form_name='player'+player.id" ></div>
    <input type="text"
           placeholder="Your Name"
           ng-model="player.name"
           name="{{player.form_name}}"
           required/>


           <ng-messages for="setPlayersForm[player.form_name].$error" ng-if="setPlayersForm[player.form_name].$touched">
              <ng-message when="required" class="alert-box alert">This field is required</ng-message>
          </ng-messages>
  </div>
</form>

JS:

var app = angular.module('plunker', ['ngMessages']);

app.controller('MainCtrl', function($scope) {

  $scope.players = [{
    name: "jhon",
    id:1 
  },
  {
    name: "jhon1",
    id:2 
  },
  {
    name: "jhon2",
    id:3 
  },
  {
    name: "jhon3",
    id:4 
  }
    ];
});

Answer №3

When using ng-form, it is important to follow these steps:

  1. Place the form name at the same level as ng-repeat.
  2. Assign the name attribute to your controls.
  3. Refer to the ng-message with formName.controlName.$error.

    <div ng-form="setPlayersForm" ng-repeat="player in rp.KillerService.getPlayers() track by $index" class="name-input">
        <input type="text" name="playerName"
           placeholder="Your Name"
           ng-model="player.name"
           required/>
        <a class="fa fa-trash-o" ng-if="player.newPlayer" ng-click="rp.removePlayer(player)"></a>
    
        <ng-messages for="setPlayersForm.playerName.$error" ng-if="rp.submitted">
            <ng-message when="required" class="alert-box alert">This field is required</ng-message>
        </ng-messages>
    </div>
    

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

both modules loading at the same time in AngularJS

var moduleA=angular.module("MyModuleX",[]); moduleA.controller("MyControllerX",function($scope){ $scope.name = "John X"; }); var moduleB=angular.module("MyModuleY",[]); moduleB.controller("MyControllerY", function($scope) { $scope.name = "Sarah Y" ...

"Chrome is throwing an unanticipated error for bigpipe.js with an uncaught syntax error related to

I have integrated the bigpipe.js method into my website to display a newsfeed. It functions properly on all browsers except for Google Chrome, where it shows an 'uncaught syntaxerror unexpected token =' error. I need assistance in resolving this ...

What is the advantage of utilizing AngularJs .constant() over simply declaring a JavaScript const variable?

Currently, I am involved in a project using AngularJS where we have implemented a .constant() provider to define some fundamental details that are utilized throughout the entire project. An example of this would be specifying a cookie name like so: .const ...

Using the AngularJS directive with $http to handle JSON responses

Following the steps mentioned here I am using Ajax to retrieve server data which is in Json format containing markup with a directive. I am attempting to use $compile to trigger this directive, but so far, I have been unsuccessful. Below is the controlle ...

When Django encounters a request with the method "POST," it mistakenly interprets it as a "GET" request

I recently encountered a problem with an AJAX request that I haven't been able to resolve. Here's the code snippet in question: <script type="text/javascript"> $('#activeform').on('submit', function(event){ ...

Can JavaScript be used to save data to a file on a disk?

As a beginner to intermediate programmer exploring AJAX, I was intrigued while learning about JavaScript. It caught my attention that many examples I have come across incorporate PHP for this task. While some may say 'I'm going about it the wrong ...

Incorporating Mongoose Schema structures into my NextJS webpage

I am new to NextJS and seeking assistance with an issue I am facing. I have defined 2 Mongoose schemas and using one on my page without any problems. However, when I try to import the second schema, my page fails to render and throws an error. Regardless ...

Trouble with the navigation of the JavaScript image gallery: next and previous buttons are not

Is it possible to have multiple galleries on a single page with captions? I've been trying to incorporate this JavaScript code, but struggling to make the next/previous links function for both galleries. Since I'm new to JavaScript, any advice or ...

Unable to interact with options in a dropdown menu while utilizing selenium

As a newcomer to the world of web scraping with Python using Selenium, I am trying to extract information on tennis players from the website "https://www.itftennis.com/en/players/". The challenge I am facing is related to navigating a drop-down list of res ...

Update the background image to be smoother, with no text overlay

I am working on a website where I need to smoothly change between background images. Here is the JavaScript code I currently have: var bg=[ 'images/best.jpg', 'images/61182.jpg', 'images/bg.jpg' ...

Repairing the orientation in unique threejs capsule geometric shape

Exploring the realm of custom geometry in three.js, I decided to experiment with modifying Paul Bourke's capsule geometry example. However, as I delve into creating my own custom capsule geometry, I have encountered two main challenges: The orienta ...

Using Material-UI with @emotion/cache in SSR results in consistently empty cache

After transitioning my React SSR from pure @emotion to material-ui 5.0, I encountered an issue where the styles no longer get extracted. The ID extraction in createExtractCriticalToChunks seems to be functioning correctly, but the cache.inserted object fro ...

Testing the scope of an Angular directive

Encountering an issue with the unit test In my code, I have: describe('test controller', function () { var =$compile, scope, rootScope; beforeEach(module('myApp')); beforeEach(inject(function (_$compile_, _$rootScope_) { ...

Managing errors in AngularJS via global $http event handling

I am in need of a way to globally intercept specific error scenarios involving $http requests, so that controllers do not have to handle these errors individually. I believe using an HTTP interceptor is the solution, but I am unsure how to prevent controll ...

Display a tooltip for ever-changing content

My HTML code displays dynamic rows with information, along with an image link that reveals specific details about the clicked row using the compentence_ID field. echo "<td>".$compi['Competence_ID']."</td>"; ec ...

Assign a variable to set the property of a class

Could something similar to this scenario be achievable? const dynamicPropName = "x"; class A { static propName = 1 // equivalent to static x = 1 } A[dynamicPropName] // will result in 1 or would it need to be accessed as (typeof A)[dynamicPropN ...

Retrieve JSON data and use a button to sort and display markers on a Google Map

Is it possible to modify my function in order to use different PHP files with separate buttons without duplicating the code? Currently, I have a function that displays markers on an external HTML page when a button is clicked. The data is retrieved from fi ...

Setting a default value for the longText field in Laravel

I have come across an issue in Laravel where I am unable to assign a default value to longText or text fields. Specifically, I am dealing with a field called "body" that will likely contain some text or HTML. How can I set a default value for this field ...

Dynamically switch between doubling Ajax calls in JavaScript

Encountering an issue with a jQuery click function. Triggering the click event on an HTML button dynamically loads styled checkbox and toggle switches based on their stored on/off state in a database. An additional click function is added to each loaded t ...

Getting the correct JSON field value from a JavaScript Promise object in the right way

Trying to fetch data in JSON format from a URL, I encountered an issue where the value of responseData.title differed between two calls made within the second .then() function below: var getTitleForId = async function(id) { if (!id) return fal ...