Trouble with AngularJS form validation not displaying

I am struggling to display error messages using the AngularJS form validation code below. It involves a nested loop where I attempt to validate a dropdown box with questions and their corresponding answers. Here is a snippet of the code:

HTML

<form name="frm" ng-controller="Contract" novalidate>
<div>
  <div ng-repeat="variable in randomQuestionList">
      <div ng-repeat="(key, pair) in variable"> 
          <select style="width:450px" ng-model="selected" ng-options="var.questionDes for var in pair"/>    
            <option value=""> Choose a question</option> 
          </select>
      </div>

      <label for="Answer" >Answer: </label>
      <input type="text" name="answer{{$index}}" ng-model="answers[$index]" ng-maxlength="50" required></input><br>
      <div ng-show="frm.answer{{$index}}.$dirty && frm.answer{{$index}}.$invalid">
        <span ng-show="frm.answer{{$index}}.$error.required"> Answer is a mandatory field. Please enter the answer </span>
        <span ng-show="frm.answer{{$index}}.$error.maxlength"> Maximum 50 characters are allowed </span>
      </div>

  </div>
</div>
</form>

JS

app.controller('Contract', ['$scope', function($scope) {

        $scope.answers = [];
    $scope.randomQuestionList = 
    [
      {
        "questionList": 
        [
            {
              "questionDes": "What is the first name of the person you first kissed?",
            },
            {
              "questionDes": "Where were you when you had your first kiss?",
            }
        ]
      },
      { 
        "questionList": 
        [
            {
              "questionDes": "What was the name of your elementary / primary school?",
            },
            {
                  "questionDes": "What was your favorite place to visit as a child?",
                }
            ]
          }
       ];
  }]);

Answer №1

When faced with a similar situation, I decided to tackle it by utilizing child forms to segment the scope. Perhaps this method could be effective for you as well.

<form name="frm" ng-controller="Contract" novalidate>
<div>
  <div ng-repeat="variable in randomQuestionList">
      <div ng-repeat="(key, pair) in variable"> 
          <select style="width:450px" ng-model="selected" ng-options="var.questionDes for var in pair">    
            <option value=""> Choose a question</option> 
          </select>
      </div>  

      <ng-form name="frmChild">
        <label for="Answer" >Answer: </label>
        <input type="text" name="answer1" ng-model="answers[$index]" ng-maxlength="2" required><br>
        <span ng-show="frmChild.answer1.$dirty && frmChild.answer1.$invalid">
          <span ng-show="frmChild.answer1.$error.required"> Answer is a mandatory field. Please enter the answer </span>
          <span ng-show="frmChild.answer1.$error.maxlength"> Maximum 50 characters are allowed </span>
        </span>
      </ng-form>
  </div>
</div>
</form>

To see this approach in action, check out the working demo here

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

How can data be transferred between web pages using jQuery or JavaScript?

Imagine having two different pages on a Classified car website: The first page is the search page, which displays a list of all cars. Check out a sample search page here The second page is the details page, where you can find specific information about a ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

AngularJS continues to display an "Invalid Request" message whenever the requested resource is unavailable

When I try to fetch a group of images through AJAX and exhibit them on the page using ng-repeat, an issue arises with the image source tags. These tags send incorrect requests to the server before the collection is retrieved, leading to error messages in t ...

Why does Angular.js promise keep returning [Object object]?

Trying to fetch an object through a promise in the service, but facing issues with data transfer to the controller. Call from the controller: dataService.getSpanishOverviewByID(newItem, api) .then(getSpanishOverviewByIDSuccess) .catch(errorCallback); T ...

Struggling with the integration of a custom login feature using next-auth, leading to being constantly redirected to api/auth/error

Currently, I am facing a challenge while working on my Next.js application. The issue lies with the authentication process which is managed by a separate Node.js API deployed on Heroku. My objective is to utilize NextAuth.js for user session management in ...

Retrieving the initial entry from a JavaScript ES2015 Map

I am working with a Map structured as follows: const m = new Map(); m.set('key1', {}) . m.set('keyN' {}) The Map may contain one or multiple items. I am wondering if there is a way to retrieve the first item by index, without using m. ...

Comparing Two Arrays in AngularJS and Disabling on Identical Cases

I currently have two tables: "Available subject" and "Added subject" which are populated by ng-repeat with two separate lists of objects. My objective is to accomplish three things: 1 - When the user clicks on the plus sign, a row with identical content s ...

Upon clicking the IconButton within the ImageListItemBar, reveal the image within a Material-UI Dialog

import * as React from 'react'; import Box from '@mui/material/Box'; import ImageList from '@mui/material/ImageList'; import ImageListItem from '@mui/material/ImageListItem'; import ImageListItemBar from '@mui/m ...

Printing incorrect value in $.ajax call

I came across this code that I have been working on: var marcas = { nome: '', fipeId: '' }; var marcasVet = []; var select; $.ajax({ dataType: "json", url: 'http://fipeapi.wipsites.co ...

Empty value for $_POST variable following xmlhttp request

When my code makes an xmlhttp request to a php file with an ID for record deletion from the database, I encounter an issue. The error message 'comicID' is undefined shows up when attempting to delete. This signifies that the variable containing t ...

Implementing a dynamic background change based on the current date in JavaScript

Is it possible to change the background of the body element based on the season using JavaScript? Here is a code snippet that demonstrates how to achieve this: // Function to determine the current season in the southern hemisphere // If no date is prov ...

Enhancing the appearance of dropdown menus for WooCommerce Variable products with custom CSS styling

I currently have a Wordpress website with WooCommerce and several variable products. Each product's variation has a dropdown menu that displays different options when clicked. My main concern is how to customize the appearance of these dropdown menus ...

Chrome and Firefox: Images cling together

I've encountered an issue with my recently launched website. Some images in a grid appear to be stuck together, but this problem only occurs in Firefox and Chrome browsers. Oddly enough, zooming in to around 110% then back to 100% seems to temporarily ...

Tips on updating service variable values dynamically

I need to update a date value that is shared across all controllers in my website dynamically. The goal is to have a common date displayed throughout the site by updating it from any controller and having the new value reflected on all controllers. Can yo ...

Passing parameters to an Angular 2 component

When it comes to passing a string parameter to my component, I need the flexibility to adjust the parameters of services based on the passed value. Here's how I handle it: In my index.html, I simply call my component and pass the required parameter. ...

How can one determine the dimensions of the browser window using a property?

Can someone please clarify how to find the width and height of the browser window specifically? Thanks in advance! ...

Best practices for including jQuery in ASP.NET (or any other external JavaScript libraries)

Can you explain the distinctions among these three code samples below? Is there a preferred method over the others, and if so, why? 1.Page.ClientScript.RegisterClientScriptInclude(typeof(demo), "jQuery", Re ...

Holding out for a callback response in AngularJS / Ionic is key

Is there a way to delay the return of the result until after receiving a callback response? I am working with Ionic and AngularJS. ...

Strategies for disabling middle mouse button default behavior in Vue

When I use @click.middle.stop.prevent="test", the default scroll wheel still shows up despite it detecting the middle mouse click and calling my function. Is there a way to prevent this from happening? ...

Executing SQL queries in JavaScript using PHP functions

Is it allowed, or is it a good practice? It worked for me, but what issues might I face in the future? Just to clarify, I am new to PHP scripting. // button <button type="button" class="btn btn-primary" id="Submit-button" >Save changes</button> ...