Sending data from an external input field to a form using AngularJS programmatically with element name

I am facing a challenge where I need to include an Input element in a Form, even though the Input is located outside of the form. While I have managed to add the input using form.$addControl(outerInput), it is not producing the desired outcome as shown in the console output.

To elaborate, I am adding the external input element to the form using form.$addControl(outerInput).

const MyApp = angular.module('app', []);

MyApp.controller('formCtrl', ['$scope', '$element', function($scope, $element){
  
    $scope.dataModel = {
      name: 'robert arschfick',
      email: 'blabla',
      age: 25,
      text: 'text'
    };
  
  
    $scope.addOuterInputToForm = function(form, inputID){
      // annoying as hell, I am retrieving the input element;
      var input = angular.element(document.getElementById(inputID))[0];
      
      form.$addControl(input);
      console.log(form);
    };
}]);
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app" ng-controller="formCtrl">
  <form ng-submit="" name="testForm">
    <input type="name" ng-model="dataModel.name" name="name" required>
    <input type="email" ng-model="dataModel.email" name="email" required>
    <input type="number" ng-model="dataModel.age">
   
  </form>
  
  <!-- I need to add this input the same way the inner inputs name 
       and email are published to the form, so that it is addressable
       via its name in the form and that it is part of the form.controls
  -->
  <input type="text" required id="inputToAdd" name="text"
         ng-model="dataModel.text">
  <button ng-click="addOuterInputToForm(testForm, 'inputToAdd')">
     Add Control
  </button>
</div>

Following the addition of the input as a control, I have observed that the object structure differs and does not contain all the necessary ng $validators. Additionally, I require it to be added by name as a property to the form, similar to how "email" and "name" are added:

https://i.stack.imgur.com/gg0Vw.png

The image showcases the external input that has been included in the form. It lacks the ng-form attributes visible in the subsequent image.

https://i.stack.imgur.com/chfNe.png

This other image depicts the internal addition of the email input to the form, containing all the ng form properties like $untouched, $prestine, etc.

https://i.stack.imgur.com/HA3FH.png

Therefore, my objective is to somehow simulate this internal addition of the external input programmatically so that it is structured within the form in the same manner as the inner inputs "email" and "name".

I apologize for any language limitations and I hope my explanation was clear enough. Thank you in advance :)

Answer №1

When using the $addControl method, it is important to note that you need the ngModelController of the <input>, not the <input> element itself.

To access the ngModelController of the element, place it within a div that has an ng-form directive:

  <div ng-form="other">
     <input type="text" required id="inputToAdd" name="text"
            ng-model="dataModel.text">
  </div>
  <button ng-click="testForm.$addControl(other.text)">
     Add Control
  </button>

Check Out the DEMO Below

const MyApp = angular.module('app', []);

MyApp.controller('formCtrl', ['$scope', '$element', function($scope, $element){
  
    $scope.dataModel = {
      name: 'robert arschfick',
      email: 'blabla',
      age: 25,
      text: 'text'
    };
  
}]);
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app" ng-controller="formCtrl">
  <form ng-submit="" name="testForm">
    <input type="name" ng-model="dataModel.name" name="name" required>
    <input type="email" ng-model="dataModel.email" name="email" required>
    <input type="number" ng-model="dataModel.age">
   
  </form>
  
  <!-- I need to add this input the same way the inner inputs name 
       and email are published to the form, so that it is addressable
       via its name in the form and that it is part of the form.controls
  -->
  <div ng-form="other">
     <input type="text" required id="inputToAdd" name="text"
            ng-model="dataModel.text">
  </div>
  <button ng-click="testForm.$addControl(other.text)">
     Add Control
  </button>
</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

The video on Videojs fails to show up on the screen

Currently utilizing the most recent version of videojs. Referencing this example http://jsfiddle.net/swinginsam/NWbUG/#share Access source code Having trouble identifying the issue. <!DOCTYPE html> <html> <head> <title>Video.j ...

Utilizing JQuery and Jade to extract and display information from a Node.js server

I am currently working with the Jade framework for frontend and using Node.js & express for backend development. When rendering a view with data, I am encountering an issue where I can't access this data using JQuery. Below is my service in Node.js ...

Hide a div element upon selecting an option from a dropdown menu

On iPhone 6plus and lower, I created a dropdown menu that opens when users click on "jobs" or "contact." However, after clicking on these options, the drop-down menu remains open. How can I make it hide automatically after a list item is clicked at this sp ...

Fetching information from WebMethod with Jquery Ajax in c#

I have a jQuery variable that contains the following values: var data = [['Vikas', 75], ['Sumit', 55], ['Rakesh', 96], ['Shivam', 123], ['Kapil', 34], ['Rana', 104]]; Now, according to my requir ...

Converting an object of objects into an associative array using Javascript and JSON

Using AngularJS, I am sending this data to my API : $http.post('/api/test', { credits: { value:"100", action:"test" } }); Upon receiving the data in my nodeJS (+Express) backend, it appears as follows : https://i.stack.imgur.com/NurHp.png Why ...

Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs? The default error message structure in NestJS looks like this: { "statusCode": 400, "error": "Bad Request", "message": [ { "target": {} ...

Developing personalized field validation in Angular

I'm encountering an issue with my code on Plunkr where the form.name.$invalid is always true, even though I expected it to be false based on Angular's documentation. It seems like the $invalid value is being set by the javascript code where ctrl. ...

When a function is included in an object, it transforms into something other than a function

In my model, it looks like this: export default class UserObject { name: string; id: string; validateInsert() { } } If I interact with the model in this way: const modelUser: UserModel = new UserModel(); modelUser.ID = 1; modelUser ...

How can we address the tagging directive problem of binding tags as an array of JSON objects and ensuring that tagging functions properly with the ng-keypress event?

Check out this plnkr example. I'm having trouble binding my tags list with ng-model. I want to bind the tags as an array of objects on a function call using ng-keypress, and then post it to a json file in a specific format. Here is what I am looking f ...

Angular 2 Update RC5: Router Provider Not Found

I'm encountering an issue with the latest Angular 2 RC5 router (router version is RC1). Below is the error log from the dev console: EXCEPTION: Error in /templates/app.component.html:2:0 ORIGINAL EXCEPTION: No provider for Router! This is how my ap ...

Execute a PHP script to modify a section of a PHP file

I successfully implemented a piece of code into a PHP file by manually searching for the right section and inserting it. Now, I am looking to automate this process with an install script for my code. The ideal installation script would: 1. Copy the exist ...

A step-by-step guide to invoking a function upon submitting a form with an external JavaScript file

How can I execute a function when the user submits a form using an external JavaScript file? index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>example</title> ...

"Troubleshooting: Why are errors not appearing in ts-node

Whenever I encounter an error in my code while compiling with ts-node, the error does not seem to appear in the console. For instance:let data = await fs.readFileSync(path); In the following code snippet, I am using "fs" to read a file by passing a path ...

Adjust the height of an element using CSS based on the height of another

Is there a way to have two divs per row, where the second div always displays its full content and the height of the first div matches the height of the second div? If the content in the first div exceeds the height, it should be scrollable. I've atte ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

Switch button displaying stored data in sessionStorage

I am facing an issue with my small toggle button in AngularJS. I have set up sessionStorage to store a value (true or false), and upon page load, I retrieve this value from sessionStorage to display the toggle button accordingly. Depending on the value sto ...

Styling CSS for disabled nested elements

In a project I am currently working on, I've noticed that disabled items do not appear disabled enough. My initial plan was to easily address this issue with some CSS. Typically, adjusting the opacity is my go-to solution to achieve the desired effec ...

What is the best location in Backbone.js to store code unrelated to the view, such as ads and analytics?

In my development of a backbone.js application, I have come to understand the role of each backbone "class" as follows: Model: This represents the data object, where the outcome of an API call is stored. Collection: An organized group of models, for exam ...

Is there a glitch in the three.js loadOBJMTL loader?

Encountering an issue with the OBJMTL loader in three.js. I'm working with obj/mtl/jpeg files and getting load errors that look like this: "THREE.OBJMTLLoader: Unhandled line 4033/5601/6659" OBJMTLLoader.js:347 Seems like there is a problem with a c ...

A guide on updating the Date Textfield value in Material UI

In my data structure, I have an array of objects with unique ids and date values. For instance, the array named stepDates might appear like this: [ { id: 1, date: "2021-07-23" }, { id: 2, date: null }, { id: 3, d ...