Building forms within an AngularJS directive

I recently developed an AngularJS directive that includes a form. This form consists of a required text field along with two additional child forms. Each child form also contains a required text field.

The distinguishing factor between the two child forms lies in how I implemented them:

  1. The first child form is compiled and added to a div.
  2. The second child form is directly inserted into the template of the directive.

Interestingly, when the second child form is invalid, it renders the entire outer form invalid as well, which was my intended behavior. However, if the first child form (the one I manually compiled) becomes invalid, it does not affect the validity of the parent form. Why is this the case?

https://i.sstatic.net/HtuRG.png

var app = angular.module('plunker', []);

app.component('generator', {
    template: "<ng-form name=\"outterForm\">" + 
                  "<input name=\"out\" ng-model=\"$ctrl.out\" ng-minlength=\"5\" ng-required=\"true\" type=\"text\" />" + 
                  "<div id=\"component-container\"></div>" +
                  "<my-text></my-text>" +
                  "<div>Valid outterForm: {{outterForm.$valid}}</div>" +
              "</ng-form>",
    controller: function($compile, $scope, $document) {
        var componentContainer = $document.find('#component-container');
        var template = "<my-text></my-text>";
        var childScope = $scope.$new();
        var result = componentContainer.append(template);
        $compile(result)(childScope);
    }
});

app.component('myText', {
    template: "<ng-form name=\"innerForm\"><input name=\"name\" ng-model=\"$ctrl.name\" ng-minlength=\"5\" ng-required=\"true\" type=\"text\" />Valid innerForm: {{innerForm.$valid}}</ng-form>"
});

Check out the live Plunker demo here:

https://plnkr.co/edit/YfBRY4xPvKgqDtWXFMUi

Answer №1

One reason for this issue is that the $$parentForm of the sub-form's formController is not being properly set after compiling the sub-form. Understanding why this happens requires a deeper level of knowledge.

I experimented with using $compile()() at different compilation stages (preLink, postLink) but encountered the same result. However, I did find two methods that almost achieved the desired outcome:

  • The first method involves directly assigning $$parentForm like so:
    childScope.innerForm.$$parentForm = scope.outterForm;
    . You can view my example on Plunker (note that I changed components to directives for flexibility).
  • The second method entails recompiling the parent form, although this renders manual sub-form compilation redundant. Here is the example on Plunker.

However, both methods present a significant challenge - setting dynamic names and models for sub-forms (which is essential for utilizing one directive across multiple sub-forms).

In the first method, there are no errors, but a bug exists: changing the model of the second sub-form also alters the model of the first one (this stops once you adjust the first sub-form's model).

The second method appears to work smoothly on the surface, yet behind the scenes, numerous errors occur every time a model is modified.

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 best way to enforce constraints on three keys when validating an object using Joi?

Currently experimenting with Joi for object validation. Able to validate objects with constraints on two keys using any.when(). Now looking to implement validation with constraints on three keys, for example: var object = { dynamicPrize: false, ...

The functionality of Protovis JavaScript is not supported within a dropdownlist's onchange event

I encountered an issue where one block of code works fine on its own, but when combined with another block, only one of them functions properly. The problem arises when I try to invoke a method from a dropdownlist using the onchange event, especially afte ...

Utilize middleware nesting in Express.js

I am interested in implementing middleware to validate requests based on a RAML file. Below is an outline of my current code: // dependencies let resources = require('osprey-resources'); let errorHandler = require('request-error-handler&apo ...

Having trouble with ASP.NET MVC when using Ajax.BeginForm and getting a blank view as a

I am facing an issue with my webpage that has multiple input fields where I'm utilizing Ajax.BeginForm to create a form for each set of inputs. <% using (Ajax.BeginForm(new AjaxOptions() { InsertionMode = InsertionMode.InsertAfter, HttpMethod = "P ...

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

The problem of "undefined function appendTo" is causing issues

My jQuery code looks like this: $(function() { var productTextTemplate = $('#product-text-template').html(); var productTemplate = $('product-template').html(); var product = productTextTemplate.appendTo(productTemplate); a ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

terminate a node-cron task or abort a node-scheduler job

I'm currently working on a nodejs project that involves managing multiple cron jobs. However, I've encountered an issue when attempting to cancel these jobs. Here's the scenario: I have set up several cron jobs using node-cron or node-sch ...

Discover the most affordable price from an array in Vue Js

One of the challenges I'm facing involves working with an array that loops through all the trips for a listing. <span v-for="price in listing.trips"> <div class="price">{{ price.cost }} </div> </span> I'm wonderin ...

Conceal div elements and retain their status when the page is reloaded or switched

I currently have 3 div elements displayed on a webpage: header-div fixed_menu_div page_cont Each of these divs are styled with the following CSS properties: #header-div { top:0; left:0; display:inline; float:left; } #page_cont { mar ...

leveraging a Nuxt plugin and saving it in middleware

My goal is to create a middleware that validates the authentication and entitlement of users. The authentication details are retrieved from my store: //store/index.js const state = () => ({ auth: { isLoggedIn: false // more properties here } ...

What is the best way to position my logo on top of the stunning space background?

Click here to check out the code on CodePen Please take a look at my code on codepen.io. I am new to Stack Overflow so please be patient with me if I make any mistakes. ;-; I currently have my logo (https://i.stack.imgur.com/W0nWc.png) included in the co ...

Tips for utilizing a printer to print HTML content in PHP

I've stored HTML content in a variable as shown below: $message ="<div> <table align='center'> <tr><td><h1>Tipo de Documentos Report</h1></td></tr> <tr><td>< ...

Tips for stopping variables from leaking in JavaScript

I'm currently working on a JavaScript code for my task manager website. Each page has its own JS file, but I've noticed that the data saved in one file seems to leak over to the others. How can I contain these variables so that tasks don't s ...

Live calculation feature for dropdown menus

I have a form where I need to calculate the total result after submission. The package and event ID should be added together, and the guest field should always be calculated (guest value * 5). The final result should be displayed in <div id="result"> ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

What is the process for incorporating a class into a table within TinyMCE using JavaScript?

I am facing an issue with adding a class to a table. I'd like the following code: <table></table> to transform into this code by clicking a button in tinymce. <table class="try-class"></table> I have added a button, bu ...

Removing items from a JavaScript list

I am seeking assistance with an issue I am facing. I have a function that generates a list based on user inputs. For instance, when a user enters apples, the function adds it to a <ul> list. My concern is about deleting specific inputs from the lis ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

What is the best way to pass the "$user" variable in a loadable file using ajax?

Is there a way to send the variable user to the mLoad.php file before executing this script? Any suggestions would be greatly appreciated. Thank you! $(document).ready(function(){ $("#message_area").load('mLoad.php'); $("#userArea").submit(func ...