I'm currently working on a form where I need to send the data to the backend in JSON format. The challenge I'm facing is that some of the form fields should be used to populate an array.
Here's an abridged version of the form (using a Jade template):
div(ng-controller="NewProposalController as newProposal")
form(name="form", method="POST")
div
label Project:
input(type="text", ng-model="proposal.project")
div
label Contact name:
input(type="text", ng-model="proposal.contacts[0].name")
label email:
input(type="text", ng-model="proposal.contacts[0].email")
div
label Contact name:
input(type="text", ng-model="proposal.contacts[1].name")
label email:
input(type="text", ng-model="proposal.contacts[1].email")
button(ng-click="create(proposal)") Save
Condensed version of the controller:
App.controller('NewProposalController', ['$http', '$scope', '$window',
function($http, $scope, $window) {
$scope.master = {};
$scope.create = function(proposal) {
$scope.master = angular.copy(proposal);
$http.post('/proposals/proposal/create', $scope.master)
.success(function(data, status, headers, config) {
$window.location.href = headers('redirectURL');
});
};
}]);
The expected JSON structure to be sent to the server looks like this:
{
"project":"Some project name",
"contacts":[
{
"name":"John",
"email":"john@example.com"
},{
"name":"Paul",
"email":"paul@example.com"
}
]
}
However, upon clicking the "Save" button, I encounter the following error message: TypeError: Cannot read property 'name' of undefined
Can anyone provide guidance on how I can ensure my contact input texts correctly populate a JSON property as an array?