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

Discovering the quantity of arguments passed into a constructor in Node.js

In my Node.js code, I have a constructor that looks like this: function Tree() { //Redirect to other functions depending on the number of arguments passed. } I then created instances of objects like so: var theTree = new Tree('Redwood'); var ...

Displaying data-table with only the values that are considered true

Right now, I am utilizing the AgReact table to exhibit data fetched from my endpoints. The data-table is functioning properly, however, it seems to be unable to display false values received from the endpoints on the table. Below are the snippets of my cod ...

What is the best way to save and retain cache data for an audio file?

I have a website where I am using an audio file in .swf format. This audio file can be turned on and off with the options provided: AUDIO ON and AUDIO OFF. However, I am facing the issue that the audio keeps playing repeatedly even after being turned off. ...

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

Add the child's input query first and then concentrate on it

I have successfully appended a div with a child input, but I am facing an issue where the newly appended input is not getting focused when added. $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper ...

The Kendo UI Combobox triggering the change event twice

After noticing some strange behavior in all the comboboxes within my application, I realized that the Kendo UI ComboBoxes were triggering the change event twice, resulting in two HTTP requests being made when the code inside only required one. Despite cond ...

Wrapping a group of elements with opening and closing tags using jQuery

I have a collection of distinct elements, like so: <section class="box-1"></section> <section class="box-2"></section> <section class="box-3"></section> My objective is to enclose all three elements within a div with a ...

Converting an Array with Key-Value pairs to a JSON object using JavaScript

After using JSON.stringify() on an array in JavaScript, the resulting data appears as follows: [ { "typeOfLoan":"Home" }, { "typeOfResidency":"Primary" }, { "downPayment":"5%" }, { "stage":"Just Looki ...

Step-by-step guide for dynamically including dropdown options

Is there a way to dynamically add a dropdown using JavaScript? I currently have a dropdown with numbers that creates another dropdown when selected. However, I want to add the dynamic dropdown through JavaScript. How can I achieve this? Below is the PHP ...

Custom condition in NG-STYLE fails to trigger

Here is a simplified representation of an item in a remote datasource: [ { "id": "3", "card_name": "Free Beer!", "count": "1" } You have a DIV with an NG-REPEAT, also simplified: <div ng-repeat="card in cardDetails"> <h1>{{card. ...

what is the best way to center list items in material ui?

I have been attempting to align the list items (checkbox, text, and buttons) within a Material UI list in the center, but all my attempts have been unsuccessful. Is there anyone who knows how to resolve this issue? Your help would be greatly appreciated! h ...

Aurelia: Understanding the Integration of a View/ViewModel from an npm Package

We've decided to implement Aurelia for the frontend of our application. With multiple projects in the pipeline, we are looking to streamline the process by packaging our custom code into npm packages that can be easily integrated by developers. This w ...

Sharing details of html elements using ng-click (AngularJS)

I am currently exploring options to enable users to click on a "open in new tab" link, which would essentially transfer that HTML element into a fresh window for their convenience. I am seeking advice on how to achieve this. At the moment, I am able to la ...

When sending a POST request to a specific URL within a controller in Flask, the render_template function is not automatically

It seems like this task should be straightforward, but I feel like I might be overlooking something. Here's the gist: I have a webpage that displays specific words, each with its own unique ID. When a user selects a word, its ID is passed to a functi ...

What is the best way to programmatically disable a button in JavaScript or jQuery when all the checkboxes in a grid are either disabled or unchecked?

In my grid, one column contains checkboxes. I need to implement a feature where a button is disabled if all the checkboxes are unticked. How can I achieve this using JavaScript or jQuery? .Aspx File <asp:TemplateField HeaderText="Cancel SO Line Item"& ...

Intersecting object identification, fresh Function

I'm currently utilizing the "Sinova / Collisions" library on GitHub along with Node.js. The library can be found at https://github.com/Sinova/Collisions. I am in need of a function that allows me to delete all data at once, as the current function for ...

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...

An issue arose while attempting to pin a file on IPFS: A TypeError [ERR_INVALID_ARG_TYPE] was encountered, specifying that the argument "url" must be a string data type

Adding the files to another project resulted in an error that I am struggling to understand. When running "node scripts1/runScript.js", the error message received is as follows: Error occurred while pinning file to IPFS: TypeError [ERR_INVALID_ARG_TYPE]: ...

When the submit button on the signup form is pressed, two distinct actions are activated to achieve specific outcomes

I am seeking assistance in implementing code that will trigger the following action: Upon clicking the 'Submit' button on a signup form after the subscriber enters their email address and name, the signup page should reload within the same tab wi ...

Obtain the count of unique key-value pairs represented in an object

I received this response from the server: https://i.stack.imgur.com/TvpTP.png My goal is to obtain the unique key along with its occurrence count in the following format: 0:{"name":"physics 1","count":2} 1:{"name":"chem 1","count":6} I have already rev ...