I am currently working on a project that involves creating a dynamic form using AngularJS. I have been referring to a helpful video for guidance here.
However, I have encountered an issue where the submitted data is returning as undefined in my controller.
The form data is being resolved in ui-router before the state is loaded and then copied to the controller's data property.
In contrast to the video, our form requires questions to be organized into sections.
We use ng-repeat to iterate over each section in the data, followed by a nested ng-repeat to loop through each question. The directive for the question/field type is loaded via ng-switch based on the type of question.
To better illustrate this, I have created a small Plunker example: https://plnkr.co/edit/6dCnHiFDEYu03kfX07mr
One challenge I have faced is how to handle certain types like address or phone number, which are considered one question type but consist of multiple fields.
For example: [Street] [City] [State] [Zip]
Here is the structure of the Controller:
namespace portal.dashboard.form{
class formCtrl{
formData: portal.domain.interfaces.IHousingRequest;
static $inject = ["formResolve"];
constructor(private formResolve:any) {
this.formData= this.loadHousingRequestFormData;
}
public submit(isValid,data) {
if (isValid) {
console.log(data);
}
}
}
angular
.module("portal")
.controller("formCtrl", formCtrl);
}
And the Directive for input type text:
namespace portal.directives {
function inputText(): ng.IDirective {
return {
scope: {
model: '='
},
controller: function ($scope: ng.IScope) {
var directiveScope = $scope.$parent.$parent;
},
controllerAs:'vm',
templateUrl: 'form/templates/input-text.html'
}
}
angular
.module("portal")
.directive("inputText", inputText);
}
HTML snippet for input type text:
<input type="text"
ng-model="model"/>
Here is a snippet of the HTML code:
<form name="form" ng-submit="vm.submit(form.$valid, data)" novalidate>
<!-- Section repeat -->
<div ng-repeat="section in vm.formData.sections track by $index">
<section>
<div>
<h4>
{{section.name}}<br />
<small ng-show="section.description">{{section.description}}</small>
</h4>
</div>
<section>
<!-- Section questions repeat -->
<div ng-form="formFields" ng-repeat="field in section.fields track by $index">
<label>
{{field.name}}<br />
<small>{{field.description}}</small>
</label>
<!-- input field switch -->
<div ng-switch="field.type">
<div ng-switch-when="Text">
<input-text model="data.answer[$index]">
</input-text>
</div>
<div ng-switch-when="Email">
<input-email model="data.answer[$index]">
</input-email>
</div>
</div>
</div>
</section>
</section>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>