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

How to dynamically display a div in Vue.js depending on the attributes of another element

I have a dilemma with my text container. My goal is to collapse the div if the text length exceeds a certain limit, and then display a button that says "...show more". When this button is clicked, the div should expand. Clicking it again should collapse th ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

What is the best way to integrate a PHP page with its own CSS and JavaScript into a Wordpress page?

I'm facing a challenge with integrating a dynamic PHP table into my WordPress page. Despite working perfectly when opened locally, the CSS and JavaScript used to create the table are not functioning properly when included in a WordPress page via short ...

Connecting with Node JS, utilising the power of Socket.IO, Express, and establishing

Hey everyone, I have an interesting concept that I'd like to discuss with you to get your thoughts on its feasibility. The idea is to set up an RFID reader connected to a MacMini (with the Mini hidden and only the RFID visible). An iPad would also be ...

Utilizing middleware with express in the proper manner

Hello there! I'm just double-checking to see if I am using the correct method for implementing middleware in my simple express app. Specifically, I am trying to ensure that the email entered during registration is unique. Here's an example of wha ...

Service Worker unable to register due to an unsupported MIME type ('text/html') declared

Working on a project using create-react-app along with an express server. The pre-configured ServiceWorker in create-react-app is set up to cache local assets (https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README ...

I have a query related to material-ui 4, specifically the material-ui/pickers component that is reporting an error regarding a non-existent "mask" property

Recently, I upgraded a reactjs project that uses Material-UI (mui) from version 3 to version 4 by following the recommended migration guide. In the process, I also replaced material-ui-pickers 2.2.1 with @material-ui/pickers. However, after the upgrade, t ...

Incorporate a Vue.js computed property into the data retrieved from a server

Coming from Knockout.js, where observables are easily created by defining them, I'm curious if there's a similar approach in Vue.js. let vm = { someOtherVar: ko.observable(7), entries: ko.observableArray() }; function addServerDataToEnt ...

The body parser is preventing the NODE from loading on localhost

var express = require('express'); var app = express(); var bodyParser = require('body-parser'); //ISSUE LINE **app.use(parser.json);** /////////////// var todos = []; var nextTodoItem = 1; app.use(bodyParser.json); ap ...

Why do query values disappear when refreshing a page in Next.js? [Illustrative example provided]

In my current project, I am developing a simple Next Js application consisting of just two pages. index.tsx: import React from "react"; import Link from "next/link"; export default function Index() { return ( <di ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

Is there a way to connect to the event.time variable in a parent scope from a directive with an isolated scope without relying on the $parent property within

angular.module('hfp.calendar') .controller('printPreviewCntrl', ['$scope', 'htmlFromServer', function($scope, htmlFromServer){ $scope.htmlReceived = htmlFromServer; $scope.event = {}; }] ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

Steps to insert an image object into a table

Note: The image in the database is named "profileImage." I want to create a dynamic image object similar to other objects when I insert this code. { label: "Image", name: "profileImage", } It will display the image endpoint as 3704545668418.PNG and ...

Is my Socket.io application consuming excessive bandwidth? What might be causing this issue?

Upon reviewing my AWS billing report, I noticed an excessive data transfer of 495.385 GB on my socket.io application running on the EC2 instance. This amount seems too high for a small experimental website like mine. Could this be due to inefficient code i ...

React: Trying to use the map function on an empty array will result in an error

I am currently facing an issue while trying to populate a shopping cart with items. Even though I have initialized the cart as an empty array, I keep encountering the following error: TypeError: cart.map is not a function ProductContext.js:34 addItemToCar ...

AngularJS promise fails to resolve when attempting to read a file using the FileReader

Can someone assist me with a function I am trying to create in my service? I want the function to use FileReader to read a small image file and return the result in a promise to my controller. The issue is that while the file reaches the service without an ...

Techniques for triggering JavaScript on elements that have been dynamically loaded via Ajax

When it comes to ensuring that a certain functionality works both when the document is ready and after an Ajax call, there are some considerations to keep in mind for optimal performance. An approach I found effective involves defining the desired code wi ...

I keep encountering a parser error when making an AJAX call to retrieve JSON data. It seems to be caused by

here is a snippet of code I am working on $.ajax({ type: 'GET', url: "<%=request.getContextPath()%>/manageUsers.do", cache: false, data:{ "resultType": "json", "submit": $.i18n.prop('esadmin.manage.users ...

Adding a certain number of days to a date within an existing ng-module in AngularJS

Hey everyone, I'm new to using AngularJS and I am currently attempting to incorporate one ng-module value into another ng-module date input within AngularJS. For example: if the date is 17-08-2016 and we add 20 days, the expected result should be 03-0 ...