Ways to inform ngForm that the nested form has been submitted

What I understand

Within Angular 1.3 and higher, I can utilize $submitted to determine if the specific form has been submitted successfully. This function works flawlessly when working with a form structured in the following manner:

<form name="myForm" ng-submit="register();" novalidate>
    <div>
        <input placeholder="First Name" name="name" type="text" ng-model="user.firstName" required />
        <span ng-show="myForm.$submitted && myForm.name.$error.required"> First Name is required</span>
    </div>
    <ng-form name="subForm">
        <div>
            <input placeholder="Last Name" name="lastName" type="text" ng-model="user.Name" required />
            <span ng-show="myForm.$submitted && subForm.lastName.$error.required"> Last Name is required</span>
        </div>
    </ng-form>
    <input type="submit" value="Save" />
</form>

The predicament

However, an issue arises when generating the ng-form dynamically and therefore not knowing the name of the parent form where the ng-form is nested within. This lacks essential information needed to decide when to display a validation error for the input inside the nested ng-form.

Suppose I have a directive intended for use as part of the form.

Index file

<!doctype html>
<html lang="en">
<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>

  <script src="lastNameDirective.js"></script>
</head>

<body ng-app="formExample">
  <form name="myForm" novalidate>
      <input placeholder="First Name" name="name" type="text" ng-model="user.firstName" required />
      <span ng-show="myForm.$submitted && myForm.name.$error.required"> First Name is required</span><br />
      <last-Name></last-Name>
      <br />
      <input type="submit" value="Save" />
  </form>
</body>
</html>

Directive

angular.module('formExample', [])
  .directive('lastName', function() {
    return {
      restrict: 'E',
      templateUrl: 'my-template.html'
    };
  });

Template

<ng-form name="subForm">
    <input placeholder="Last Name" name="lastName" type="text" ng-model="user.Name" required />
    <span ng-show="subForm.$submitted && subForm.lastName.$error.required"> Last Name is required</span>
</ng-form>

How can I navigate around this situation? Is there a method to dynamically retrieve the name of the form that my ng-form is enclosed in, or can I somehow monitor a submit on my parent form?

A plunker available for experimentation

Research undertaken so far

I've attempted reviewing RealCrowds Angular-Utilities, currently implemented in my ongoing project (since I've been using Angular 1.2 till now), yet it seems incapable of handling this scenario effectively. (Though conversation has touched on this topic)

Answer №1

Make sure to include the parents formController in your directive and make it accessible.

....directive('lastName', function() {
  return {
    restrict: 'E',
    templateUrl: 'my-template.html',
    require:'^form',
    link:link
  };

  function link(scope, element, attrs, formCtrl) {
    scope.parentForm = formCtrl;
  }
});

http://plnkr.co/edit/pKonBjl57bjp4PaokARV


I recommend making the parents formController accessible through the controllerAs syntax - assuming the main form has a controller. This leads to cleaner markup and eliminates the need for the require example provided above

Answer №2

Sup!

I have a solution for you:
Upon reviewing the plunkr, I noticed that the second span is hidden all the time.
The issue lies in your submit button being assigned to the main form. When checking $submit on a subForm, it does not get submitted because there is no <submit> for the subForm.
Therefore, you should always check the main form. Here's your fork.

Hopefully, this helps.

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

What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests: var information = {}; function process_information(item){ information[item.id] = item; } function perform(){ var calls = []; for(var i = 0; i < 10; i++){ var call = $.get(URL, ...

Utilize Android accelerometer data to bring objects to life with animation

Utilizing an Android app, I am streaming accelerometer data to a Python script on my PC. The data is then saved to a text file. My goal is to utilize Javascript and jQuery to animate a 3D CSS cuboid (representing the device) to replicate the movements capt ...

Ensuring Data Integrity with a Rich Text Editor

I currently have an ASP.NET MVC application where I utilize CKEditor for text input. To allow for the HTML created by CKEditor to be passed into the controller action, I have disabled input validation. The user-entered HTML is then displayed on a web page. ...

How can you stop queuing animations and timeouts in jQuery?

I'm facing a seemingly simple problem that I need help with. On my website, there's a hidden div.notification bar at the top. This bar can be displayed by adding either the success or warning class to it. There are two scenarios: either a messa ...

Determine the specific value to extract from the URL

I have modified the following script to populate a hidden form field with a value defined in the URL. The current script works, but it shows anything after "product=", including utm_ parameters. Now, I am attempting to find a way for the script to only tr ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Adjusting the dimensions of the box while the clock is ticking

I am looking to automatically resize a cube whenever a new value is entered in the input text box. I have found a similar solution that updates the cube size only when a button is clicked. http://jsfiddle.net/EtSf3/3/ document.getElementById('btn&ap ...

"Calling getElementByID results in a null value being returned (see example in the provided

In my attempt to design unique buttons for a media player, I encountered a challenge. I envisioned the play button transitioning into a "loading" button and eventually into a pause button. My solution involved using 4 div elements - stop, play, loading, a ...

Encountering an issue with Next.js React SSR using styled-jsx: unable to access the 'state' property as

I've come across a problem that I can't seem to figure out. Despite my attempts to search for a solution here, I haven't been able to help myself. I'm new to javascript and react, so please bear with me. Issue: I'm using React (1 ...

Dealing with multiple input fields that are generated using the map method in combination with react-redux

I am working on a project where I have a product list in JSON format stored in json-server. I am using React-Redux to fetch the data and render it in a table. Additionally, I have an input field where users can enter the quantity of each product. I need to ...

Node.js and Express: Delegate routes to different endpoints for handling by the Single Page Application, instead of just the root route

I have my node.js/Express server configured to host my Vue.js single page application from the root URL path (localhost:3333) within the public folder. When navigating through my app, everything works smoothly thanks to the vue.js History API handling all ...

Developing tabbed sections in XSLT

Utilizing Angular JS within XSLT, I am aiming to develop a tab-based user interface using XML data. The requirement is to generate multiple links and corresponding div elements based on the number of nodes in the XML. To manage the display of these div ele ...

Checkbox with editable ngGrid

After spending hours attempting to implement an editable checkbox element in a ngGrid, I encountered some issues. When I use a type=text input, everything works smoothly. However, as soon as I switch it to type=checkbox, it stops functioning properly. Des ...

Using JavaScript to enhance event handling for a `select` element in a progressive manner

I have an advanced <select> element in my HTML. It is structured like this: <ul> <li></li> <li></li> ... </ul> In the current setup, a click event handler is attached to each individual li element. If the ...

How to properly stop a sequence of notes using WebAudio in an asynchronous manner?

Utilizing WebAudio for playing a sequence of musical notes has been quite successful. I have a playNote function that takes note frequency, start times, and stop times for each note as input. The parameters for generating the sequence are set prior to the ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

Using JSON.parse on the output of BsonDocument.ToJson results in an error

When fetching information from MongoDB and sending it to the client, I encountered a dilemma: var retrievedBsonDocument = ... retrieve data from database ... var dtoObject = new Dto { MyBson = retrievedBsonDocument.ToJson() }; While trying to parse the M ...

Updating Directive on State Changes: A Step-by-Step Guide

Within my Angular template, I have implemented a root state that sets the overall structure. This root state includes a sidebar with dynamic menus that change based on the current state. Here is an example: .state(‘root', { abstract: tr ...

What is the best way to eliminate a particular item from an array that is nested within the object? (using methods like pop() or any

I am struggling to remove the 'hello5' from the years in myObj. Although I tried using the 'pop' prototype, an error occurred in the browser console displaying: 'Uncaught TypeError: Cannot read property 'type' of undefi ...

PHP enables users to look at manual values in columns and MySQL values row by row

I have created a PHP program to organize seating arrangements for an exam hall. The user manually inputs the names of the halls, which should be displayed in columns in a table. The register numbers are fetched from a MySQL database and should be displayed ...