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 :)