Dynamically added input elements in AngularJS are causing issues when trying to retrieve the states of form input elements

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);
        app.controller('validateCtrl', function ($scope, $compile) {
            $scope.createField = function () {
                var lname = '<label>LastName : </label><input type="text" name="last" ng-model = "last" required/> Valid: {{myForm.last.$valid}}<br>';
                var tdiv = document.createElement("div");
                tdiv.innerHTML = lname;
                $compile(tdiv)($scope);
                document.getElementById("container").appendChild(tdiv);
            }
        });
    </script>
    <body>
        <h2>Dynamic Element Creation Example</h2>
        <form ng-app="myApp"
              ng-controller="validateCtrl" 
              name="myForm">
            <div id="container">
                Firstname : <input type="text" name="first" ng-model="first" required/>
                Valid: {{myForm.first.$valid}} [ Here the element state is displayed correctly, but when adding elements dynamically with the create button, the validation status is not showing. ]

            </div>
            <button type="button" ng-click="createField();" value="Create">Create</button>
        </form>
    </body>
</html>

In this example, the element validation state is shown correctly. However, when adding elements dynamically with the create button, the validation status is not displayed.

Answer №1

The issue you're experiencing is due to compiling your dynamic inputs when they are detached, preventing them from registering themselves via the FormController. To resolve this, you must first insert your element into the DOM and then compile it immediately after. Essentially, all you need to do is move your $compile(tdiv)($scope); one line below. After making this adjustment, your code should look like this:

        $scope.createField = function () {
            var lname = '<label>LastName : </label><input type="text" name="last" ng-model = "last" required/> Valid: {{myForm.last.$valid}}<br>';
            var tdiv = document.createElement("div");
            tdiv.innerHTML = lname;
            document.getElementById("container").appendChild(tdiv);
            $compile(tdiv)($scope);
        }

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

Input information into a JSON container

I've been struggling to find a solution for this issue. Here's the JSON variable I'm working with, which includes the names "rocky" and "jhon": var names = [ "rocky", "jhon" ]; Now, I need to add a new val ...

Determine if the input value is an integer using a custom validator in Angular 2

Looking for a way to validate integer inputs in an Angular2 project? I experimented with using Number(control.value), but it returns 0 for empty fields, which is not ideal. Another method I tried was parseInt(control.value,10), but it ignores spaces. For ...

retrieve the value obtained from a promise in an outer scope

I need a simple function that returns the name. Here's my existing code snippet: getName(entity, id) { const promise = userServices.getName(entity, id).then((data) => { return data; }); / ...

Searching text with jQuery filter can be delayed when backspacing

When utilizing jQuery filter to search for names in a large list, it performs well with high speed when typing in the input field. However, upon pressing the backspace button to clear the search text, there is a noticeable delay of over 4 seconds when ther ...

What is the most effective way to accurately identify the mobile platform of a user using JavaScript?

I need to determine whether a user has accessed the application through a browser on Android or iOS. The company would like to display slightly different content depending on the platform. While I am aware that navigator.platform can be used for this pur ...

It's important to understand how to correctly send state values from a parent component to a child component

I have a tab menu in my code and I am looking to implement a feature where tabs can be switched using a button. The challenge is passing the values of these tabs into the onclick function of the button in order to navigate between them. Here is an example ...

Ensure Safari sends the Origin header in jQuery GET requests

When I send a request from https://app.example.com, the following code is executed: $.get('https://api.example.com', { foo: 'bar' }) .success(getSuccess) .error(getError); This script runs smoothly on Chrome and Firefox, however, ...

Activate/Deactivate toggle using Vue.js

new Vue({ el: '#app', data: { terms: false, fullname: false, mobile: false, area: false, city: false, }, computed: { isDisabled: function(){ return !this.terms && !this.fullname && !this.mob ...

Leverage the power of mathematical functions within Angular to convert numbers into integers

In my Angular 7 Typescript class, I have the following setup: export class Paging { itemCount: number; pageCount: number; pageNumber: number; pageSize: number; constructor(pageNumber: number, pageSize: number, itemCount: number) { thi ...

Passing a list of objects containing lists in MVC3

Is it possible for me to send an array of objects, each containing arrays, from JavaScript to a MVC action result method? Essentially, I have a KeyValuePair with keys as arrays of strings and I need to return a list of these KeyValuePairs. In my code, I ha ...

Is it possible to consolidate all ng-includes into a single HTTP request for improved efficiency?

In our main html/jsp pages, it is common to have numerous instances of ng-includes. I am curious if there is a method to combine all ng-includes into a single HTTP request? ...

What is the method for retrieving the name of the 'Autocomplete' component in Material UI?

Currently, I am faced with the challenge of working on multiple Autocomplete MUI components and am in the process of creating a "generic" event handler that will utilize the useReducer hook to manage the state. The issue lies in the fact that the onChange ...

Integrate Arduino's capabilities with Johnny-Five within an HTML JavaScript document

As a beginner in the world of JavaScript, I set out to embark on a project involving turning on a connected LED on an Arduino board by simply pressing a button on an HTML page. After doing some research, I came across a JavaScript library called "johnny- ...

AngularJS Expression Manipulation

I am looking to implement a functionality similar to the one below: HTML <mydir> {{config = {type: 'X', options: 'y'}} </mydir> <mydir> {{config = {type: 'a', options: 'b'}} </mydir> JS Dir ...

Guide to importing a JSON file into Vue.js and HTML

I'm a beginner in Vue and not very familiar with HTML I'm attempting to import data from a JSON file into my interface to display it for the user. Below is the structure of the JSON: [ { "Title": "SOFT-STARTER", "Cod&q ...

Limiting input to specific characters is effective on Chrome, but unfortunately does not function on Firefox

This code snippet is designed to restrict user input to lowercase letters from a-z, numbers from 0-9, and the dash character "-". While it functions correctly in Chrome, it does not allow any input in Firefox. What could be causing this issue? $('#sl ...

Utilize the $slots property when working with v-slot in your Vue application

When dealing with a specific use-case, it becomes necessary to retrieve the rendered width and height of a DOM element inside a slot. Typically, this can be achieved by accessing this.$slots.default[0].elm. However, complications arise when introducing sc ...

The jQuery script removal functionality originated from the use of ajax

I have adapted a nested modal script (jQueryModal) to better suit the project's requirements, but I've encountered an unusual issue that I can't seem to resolve. When I invoke the modal to load some content via ajax, and the response from t ...

Encountering the error of receiving "$ undefined," despite making a reference to the library

I have included the JQuery library in the following way: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script> Despite trying to download the library and include it locally in my project, I ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...