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

Obtaining essential data while facing a redirect situation

I need to extract the og data from a specific URL: https://www.reddit.com/r/DunderMifflin/comments/6x62mz/just_michael_pouring_sugar_into_a_diet_coke/ Currently, I am using open-graph-scraper for this task. However, the issue I'm facing is that it i ...

Customizing the layout of specific pages in NextJSIncorporating

In my Next.js project, I'm trying to set up a header and footer on every page except for the Login page. I initially created a layout.tsx file in the app directory to apply the layout to all pages, which worked fine. However, when I placed another lay ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

How can the Header of a get-request for an npm module be modified?

Currently, I am utilizing an npm module to perform an API request: const api_req = require('my-npm-module-that-makes-an-api-request'); However, I am seeking a way to modify the user-agent used for requests generated internally by the npm module ...

Obtaining the NodeValue from an input of type <td>

I have a HTML code snippet that I am trying to parse in order to extract the nodeValue of all elements within the table columns. <table id="custinfo"> <tr> <td><label>First Name</label></td> <td& ...

Pairing strings with arrays

I'm trying to compare elements in two arrays and see if there are any matches. However, I can't seem to get it working correctly. let name; let list = ["Kat", "Jane", "Jack"]; // sample array let input = ["Hey", "i'm", "Jack"]; if (input.fo ...

Attempt to retrieve JSON-formatted data from a repository on Git

As a novice, I am delving into the world of ajax and experimenting with json files. Utilizing JSON formatted data is something I am keen on mastering. However, my request seems to be yielding an empty outcome. An Update: Below is the piece of code I am wor ...

What is the best way to use jQuery to retrieve information from one child element in an XML API in order to locate another child

Hi there, I'm new to jQuery and could use some help. I'm attempting to retrieve specific information like CPU and RAM details from a particular phone model. I've written the jQuery code, but I'm having trouble displaying the RAM and CPU ...

Populate your HTML with JSON data

I need some guidance on how to achieve a specific task. I have a PHP file that retrieves data from a MySQL database and returns it in JSON format. Now, I want to display this data in HTML with "data_from_json" replaced by "18.5". Any assistance would be gr ...

Having trouble initiating a "curl:localhost:3000" connection, receiving a URI Error message

Recently delving into the realm of node js, I have embarked on a journey to start up a server and experiment with an app designed to trim URLs. However, I find myself at an impasse. Environment: Windows Text Editor: VSCode Below is my code for index.js ...

Send data from the URL to PHP and then to Javascript in order to showcase the value within an input field

I need to pre-fill an email subscriber form with an email address from the URL. The specific email address is included in the following URL: http://www.domain.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcacbdbbb9e3b9b ...

Transferring SQL-generated JSON object from PHP to JavaScript

Seeking assistance with passing a JSON object from PHP to Javascript. The object is populated from an SQL Database using the following PHP code snippet. <?php $conn = mysql_connect("localhost","root",""); if(! $conn ) { die('C ...

Error: scrollreveal JavaScript is not properly defined

Desperately seeking guidance on a particular code snippet... window.sr = ScrollReveal({ reset: true }); sr.reveal('.whitecircle, .circleStatsItemBox, .circleStat', { duration: 200 }); function circle_program() { var divElement = $(&apo ...

Utilize Google Maps to receive directions to a specific destination and discover current traffic conditions along the route using their comprehensive API

I am currently working on implementing the Google Maps direction identifier functionality with traffic details. However, I am able to obtain directions but not specific traffic details for a selected path; it seems to apply overall traffic data instead. ...

Removing all table rows except one in Jquery

I currently have this code in my view: <script> $(document).ready(function() { $("#add_instruction").click(function(){ $("#instructions").append("<tr><td></td><td><input type='text' name='rec ...

Display the page for 10 seconds continuously in a loop

I am currently developing a Node JS guessing game where data is collected on the back-end and sent to the front-end to start the game. The data consists of 10 levels, allowing the game to operate on a single page. Each level lasts for 10 seconds. Once the ...

Vuelidate allows for validation to occur upon clicking a button, rather than waiting for the field

As I navigate my way through learning vuelidate, everything seems to be going smoothly, except for one thing. I can't figure out how to trigger validation only when the "Submit" button is clicked. Currently, the fields turn red as soon as I start typi ...

Interacting between Angular controllers and services to efficiently showcase JSON information

Recently, I started working with Angular 1.5+ and I'm facing some challenges with the basics, particularly when it comes to displaying data from a JSON file on the DOM. Although I can fetch the data successfully (at least I think so, as it console lo ...

Learning the art of Javascript programming within the HTML5 realm

Seeking assistance with a JavaScript project - I'm attempting to develop a Bubble Buster game reminiscent of pong, but with multiple bubbles. The goal is to have falling bubbles on screen (roughly 100 in total) in various colors dropping from random l ...

Each time the website refreshes, Object.entries() rearranges the orders

After reading the discussion on Does JavaScript guarantee object property order? It seems that Object.entries() should maintain order. However, I encountered an issue with my Angular website where the order of keys in Object.entries() changed upon refres ...