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?

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

The size of the cursor varies depending on the line it's placed on

I have a content editable div where three lines are separated by BR tags. When I click on the second line, the cursor becomes bigger than that in the first line. .content { line-height: 35px; } <div class="content" contenteditable="true"> ...

ways to incorporate searching within JSON data using AJAX and jQuery in JavaScript

My search box needs to have JSON data appended into it. Below is the HTML code: <input type="search" id="merchantName" name="merchant" placeholder="enter merchant name"></input> I have JSON data containing merchant names that I want to appen ...

Executing REST API calls from within a loop in AngularJS

for (var i = 0; i < pricingPlans.length; i++) { productServices.retrivePricingPlan(pricingPlans[i].Id.Value).then(function (objPricingPlan) { productServices.createPricingPlan(objPricingPlan.data).then(function (objNewPricingPlan) { ...

Unexpected color changes when hovering over sparkline graphs

One of the jquery plugins I'm using is called sparkline Here's an example of how I am using it: $(function(){ $("#sparkline5").sparkline([2, 8, 10, 22], { type: 'pie', height: '140', sliceColors: [ ...

Unable to execute click events on JavaScript functions after updating innerHTML using PHP and Ajax

To begin, I want to clarify that I am intentionally avoiding the use of jQuery. While it may simplify things, it goes against the purpose of my project. Please note that 'ajaxFunction' serves as a generic example for AJAX requests using GET/POST ...

What could be the reason for webpack not making jQuery available as a global variable?

For my current project, I am utilizing several npm modules by integrating them using yarn and webpack. These essential modules include jquery, bootstrap3, moment, jquery-tablesort, jquery-ujs, bootstrap-select, and livestamp. Some of these plugins require ...

What is the best way to retrieve the specific property from a bound function?

I'm looking to retrieve the value of a specific property from a function that has already been bound. function foo(){ console.log(this.a) } const bar = foo.bind({a:1}) bar() // Outputs 1 bar.getThis() // expected result is { a: 1 } Given the code ...

Adding JavaScript dependencies in Directives in AngularJS: A Step-by-Step Guide

When working with directives in AngularJS, I have encountered a challenge. I need to ensure that my JavaScript is loaded before calling the directive. Is there a way to directly inject JavaScript into AngularJS directives? Consider the following code snip ...

Unusual behavior observed in AngularJs local variables

This code snippet is from the controller: cat1=[]; $.getJSON('categories/1/', function(data) { cat1 = data; //this returns a JSON object }); //cat2..4 are also JSONs $scope.pictures=[cat1,cat2,cat3,cat4,cat5]; The issue here seems to be th ...

The setInterval function will run just one time when triggered by an onclick event

After watching a YouTube tutorial on creating desktop notifications, I had an idea to use it as a reminder tool. For example, having a specific reminder appear as a desktop notification every 30 minutes when triggered by clicking a button. However, the cod ...

Steps to create two jQuery dropdown filters for multiple identifiers:

Is it possible to create two dropdown menus that can be used to filter a gallery of images? I am currently facing an issue where the filtering functionality is not working after adding a name attribute to the image IDs. When I select an option from the s ...

What kind of type is recommended to use when working with async dispatch in coding?

For my TypeScript and React project, I am currently working on an action file called loginAction.tsx. In this file, there is a specific line of code that handles the login functionality: export const login = (obj) => async dispatch => { dispatch( ...

Methods for altering the color of a div using addEventListener

Why doesn't the color change when I click on the div with the class "round"? Also, how can I implement a color change onclick? var round = document.querySelector(".round"); round.addEventListener("click", function() { round.style.backgroundCol ...

Issue encountered while utilizing PHP sessions

I'm currently developing a basic login page that utilizes JS, JQuery, and PHP. login.php <!DOCTYPE html> <head> <title>AJAX Login Learning Activity</title> <link rel="stylesheet" type="text/css" href="login.css"> ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

Traversing through each element using Array method

I need to create a redux function that will add a specified number n to the fourth element of an array every time a button is clicked. However, if the element is either L or M, I do not want the addition to occur. For example, starting with this initial a ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

When the class name is identical, the click event appears to be malfunctioning

Why isn't the click event working in this code? What am I doing wrong? $(document).ready(function() { $('.dashboardList').click(function() { alert("hello"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1. ...

What causes the undefined value of "this" in the Vue Composition API setup function?

A Vue component I've created is using v3's composition API: <template> <input type="checkbox" v-model="playing" id="playing" @input="$emit('play', $event.target.value)" /> <labe ...

jquery function context

I'm having trouble grasping function scope in this scenario. When a button is clicked, it triggers a dialog box with a textarea inside displaying a URL that can be copied for camera setup. <button id="axis-details" onclick="apikey('<?php e ...