Implementing dynamic ng-forms with real-time validation

My directive includes a template with an ng-form:

<ng-form name="autocompleteForm">
  <div class="form-group" show-errors>
    <input type="text" class="form-control" ng-model="ctrl.val.value" name="autocompleteField" required>

    <div class="messages" ng-messages="autocompleteForm.autocompleteField.$error">
      <span class="help-block" ng-message="required">Please, select the value</span>
    </div>
  </div>
</ng-form>

I am dynamically adding this form using ng-repeat. Everything seems to be working fine - the form itself and the validation. However, there is one issue: after the form is added, it appears to be $invalid and displays an error message. I'm unsure why this is happening and how to resolve it. Here is the object of the form after it is added:

{  
   "$error":{  
      "required":[  
         {  
            "$validators":{  

            },
            "$asyncValidators":{  

            },
            "$parsers":[  

            ],
            "$formatters":[  
               null
            ],
            "$viewChangeListeners":[  

            ],
            "$untouched":true,
            "$touched":false,
            "$pristine":true,
            "$dirty":false,
            "$valid":false,
            "$invalid":true,
            "$error":{  
               "required":true
            },
            "$name":"autocompleteField",
            "$options":null
         }
      ]
   },
   "$name":"autocompleteForm",
   "$dirty":false,
   "$pristine":true,
   "$valid":false,
   "$invalid":true,
   "$submitted":false,
   "autocompleteField":{  
      "$validators":{  

      },
      "$asyncValidators":{  

      },
      "$parsers":[  

      ],
      "$formatters":[  
         null
      ],
      "$viewChangeListeners":[  

      ],
      "$untouched":true,
      "$touched":false,
      "$pristine":true,
      "$dirty":false,
      "$valid":false,
      "$invalid":true,
      "$error":{  
         "required":true
      },
      "$name":"autocompleteField",
      "$options":null
   }
}

Some online sources discuss this behavior in relation to dynamically added forms (like this one) and they seem to experience the same issue. Is this the default behavior in Angular? Are there any options to prevent this "initial validation"?

Answer №1

To ensure that the messages container is only displayed once the form has been submitted, you can include the ng-if directive in your code like this:

<div class="messages" ng-messages="autocompleteForm.autocompleteField.$error" ng-if="autocompleteForm.$submitted">
    <span class="help-block" ng-message="required">Please make sure to select a value.</span>
</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

Running a code from a plugin in Wordpress site

I am currently utilizing the "wp-video-lightbox" plugin for WordPress, which generates small floating boxes for my videos. I am interested in incorporating variables like http://www.example.com/?video3 to provide shortcuts similar to what YouTube offers. ...

What could be causing my Node.js website to have trouble locating pages in the public directory?

Embarking on my journey in web development using node.js, I encountered an issue while trying to load a particular page, which led to the following error message in my browser: Cannot GET /public/pages/terms-and-conditions.html The file structure is orga ...

Retrieve the runtime configuration object or file using Jest

Is there a way to access the Jest runtime config object or file path? I wanted to utilize runtime config properties in my custom matchers. // ./jest.config.js const path = require("path"); module.exports = { prop1: "foo", prop2: "bar" }; // my-custo ...

Looking to capture all page requests in Nextjs 13 with the app router?

Back in Next.js 12, I was able to use the old Pages router and write pages/[...urlParts]/index.js, which would specifically catch page routes. However, now in Next.js 13 with the new App router, my app/[...urlParts]/page.js route is capturing everything, i ...

While conducting tests on a Vue single file component, Jest came across an unforeseen token

I need help with setting up unit tests for my Vue application that uses single file components. I've been trying to use Jest as mentioned in this guide, but encountered an error "Jest encountered an unexpected token" along with the details below: /so ...

How to prevent VueJS observer from monitoring a temporary variable

My VueJS and Observer objects are causing me trouble. I am encountering an issue where I assign a part of my object to a temporary variable for later use, update the original part with new data, and then revert it back to its original state after 8 seconds ...

Creating a dynamic textarea input based on the number entered using AngularJS

Can a loop be simplified in AngularJs to easily determine the number of textarea inputs a user can fill? <input type="number" class="form-control" min="1" max="4" value="1"> <div ng-repeat="..."> <div class="form-group"> < ...

Learn how to call class methods using jQuery events by utilizing the on() method

I'm attempting to create a reusable "component" using both HTML5 and accompanying JavaScript code that can be utilized multiple times. First, let's examine the HTML5 component code: <div class="listEditor" id="myStringList"> <div id="li ...

Issue: Incorrect parameters for executing the MySQL statement

Currently, I am working on a nodeJs project and utilizing the npm package mysql2 for connecting to a MySQL database. This is how my MySql Configuration looks like:- let mysql = MYSQL.createConnection({ host: `${config.mysql.host}`, user: `${config.mys ...

retrieve user photos from twitter using angular.js and firebase

As a newcomer to angular.js and Firebase, I am delving into editing code from an open-source script to expand my knowledge. I initially used a chat script with a Facebook login. However, I have decided to switch the Facebook login to a Twitter login, as F ...

Load a file in JavaScript without using the cache

I'm working on a function that reads a text file from a specific location: <html> <head> <script> function readTextFile(file){ var out_text='' var rawFile = new XMLHttpRequest(); rawFile ...

"Creating a 3D rotation effect on individual objects nested within other objects using Javascript

In my software, I've created four Physijs.BoxMesh(...) shapes, all nested within an independent object. My goal is to rotate these four physics boxes as a whole, but once they are grouped under the 5th object, they no longer respond to rotation comman ...

Utilizing JavaScript for selecting a radio button on click event

I have implemented a feature with four radio buttons to select a country. Upon clicking on any of the radio buttons, I utilize Ajax to retrieve the states corresponding to that specific country. To indicate to the end user that data processing is ongoing, ...

Invert Three.js lookAt method with camera position

Currently, I am animating objects towards the camera and aiming to have them facing the camera upon arrival. To achieve this, I am utilizing object.lookAt(camera.position) However, I am encountering a challenge in tweeing the object back to its initial ro ...

React Switch not displaying various pages correctly

After creating a new component to switch between pages on my React app, I encountered an issue where the HomePage renders correctly when entering the site, but clicking on navlinks does not work. Additionally, when trying to access the url /contacto, ins ...

Angular directive compatibility with Mozilla Firefox

I've encountered a strange issue with my directive in Firefox. The directive is designed to limit user input, and it functions correctly in Chrome. However, in Firefox, once the user reaches the input limit, they are unable to delete any characters - ...

Encountering difficulties in Laravel while trying to submit form data

I am working with Laravel and have created a form as shown below. <h1>New Comment</h1> <form method="post"> Comment: <input type="text" size="128" name="comment" value="{{old('body')}}" /></p> @if ($errors-> ...

Angular 2 - Ensuring mandatory fields are completed when checkbox is checked

Hey everyone, I'm a newcomer to Angular2 and JS frameworks in general. I've been following tutorials on the official site but I can't seem to find a solution to my problem. So, I have a checkbox that is optional, but if it is checked, a new ...

Scroll-triggered Autoplay for YouTube Videos using JQuery

Issue: I'm trying to implement a feature where a YouTube video starts playing automatically when the user scrolls to it, and stops when the user scrolls past it. Challenges Faced: I am new to JavaScript web development. Solution Attempted: I referre ...

Simple methods for ensuring a minimum time interval between observable emittance

My RxJS observable is set to emit values at random intervals ranging from 0 to 1000ms. Is there a way to confirm that there is always a minimum gap of 200ms between each emission without skipping or dropping any values, while ensuring they are emitted in ...