AngularJS allows for the population of a JSON array from user input using the ng-model directive

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?

Answer №1

When dealing with this scenario, it is necessary to set up the proposal object from the controller:

$scope.master = {};

$scope.proposal = {
    contacts: [
        {
            name: "",
            email: ""
        },
        {
            name: "",
            email: ""
        }
    ]
};

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

Increment the text counter following the uploading of an image file with html format

I have a form in which I am checking the character limit that a user can input into a text field using the 'onkeyup' attribute to update it in real time. Now, I want to achieve a similar function for image uploading. When a user selects an image ...

Guide on incorporating botframework into a mobile application...?

Recently, I developed a chatbot utilizing the MS bot framework in Nodejs. To display the chatbot in an HTML format without iframes, I incorporated a React Component from the link provided at https://github.com/Microsoft/BotFramework-WebChat. At this point, ...

The JSONObject's starting brace must be at the first character of the first line to avoid the '}' error

String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4"; JSONObject jsonObject = new JSONObject(JSON); JSONObject extractedObject= jsonObject.getJSONObject("extract"); Object item = extractedObject.get("2"); System.out.println(item); I' ...

The AngularJS directive that wraps the Kendo UI grid is unable to handle the kendoEvent properly

Our goal is to develop a displayBasket directive that will wrap kendoGrid and additional functionality. However, we are facing an issue where the gridDataBound function is not receiving kendoEvent. How can we resolve this problem? Here is an example in HT ...

When attempting to validate dates with the after: rule in vee-validate while also utilizing a computed field in Vue.js, the validation process may encounter unexpected issues

Below is a codepen with a simple input field for entering dates: <input type="text" v-model="startDate" name="StartDate" v-validate="{ required: false, date_format: 'dd/MM/yyyy', before: maxStartDate }"/> Despite e ...

Tips for implementing filters in Angular2 without using the package field in the console

I am currently experiencing an issue with a filter field in my code. The filter works fine when all the package data is present, however, some items do not have a package field. As a result, I need to filter based on the package name but I am encountering ...

Load the values into the dropdown list based on the selection from the previous dropdown menu

Currently, I am working on implementing cloning functionality for select boxes. There are 3 select boxes: country, state, city. The user selects the country first which then populates the state select box based on the ID, and similarly, the city dropdown ...

Tips for updating the value of a JSON by accessing the specific path in Java

I am trying to change the value of "$.widget.debug" in my code. I have experimented with numerous libraries, but haven't been successful in achieving this task. { "widget": { "debug": "on", "window": { "title": "Sample ...

The amazing property of AngularJS - Scope

I have saved this HTML code in a file. Here is the HTML : <!-- checkbox 1 --> <input type="checkbox" name="checkbox1" id="checkbox-group1" ng-model="checkbox1" value="group1"> <input type="checkbox" name="checkbox1" id="checkbox-group2" ng ...

What is the proper way to connect an external Javascript file to an html document within a Play Framework project?

Below is the content of my scala.html file: @() <!DOCTYPE html> <html> <head> <title> Spin To Win </title> <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/styles.css")" ...

Issue with camera boundaries in Three.js when using EffectComposer with an orthogonal camera is currently presenting inaccuracies

In reference to a previous question on Three.js, I have successfully created a scene with a "minimap" using an orthogonal camera rendering into a viewport. The minimap is displayed properly in the standard renderer. Now, I wanted to add postprocessing eff ...

ajax response is equal to zero

For the past two days, I have been attempting to solve a problem on my own. However, I am now seeking assistance as I seem to be stuck. The task at hand is quite straightforward - a jQuery AJAX request sends a username and password to a server running the ...

Trigger event when the useRef element's height surpasses zero

I have a large list of photo thumbnails, and I need to ensure that one of the thumbnails scrolls into view when the list is loaded. The photos are generated using the map function, and the container div of one of the thumbnails will be assigned a ref. I ...

Auto-updating Angular $scope variables

I am facing an issue with two variables in my code. Whenever I update one variable, the other variable also gets updated automatically. Can someone please help me understand what is causing this behavior? $scope.pages = []; $scope.pagesSave = []; var fun ...

Intelligent Scrolling with Bootstrap 4

Utilizing a basic tutorial from here to implement show/hide functionality for a standard BS4 navbar on scroll. Works flawlessly on desktop. However, facing an issue with the mobile view where the navbar behaves oddly when scrolling down and returning to t ...

What are the best methods for encoding and decoding query parameters?

Here is the current implementation of my Express.js function "Restore objects pickled into JSON strings": router.post('/restore', json_parser, function(request, response, next) { console.log('router.post /load'); console.log(&apo ...

How can I transform Json data into a jQuery datatable using ajax call?

I have successfully stored the JSON data in a variable named "msg" using AJAX. Currently, I can only display the data by alerting(msg) on the page. However, I am looking for a way to visualize this data with columns in AJAX or JavaScript using something li ...

Having trouble retrieving cookie in route.ts with NextJS

Recently, I encountered an issue while using the NextJS App Router. When attempting to retrieve the token from cookies in my api route, it seems to return nothing. /app/api/profile/route.ts import { NextResponse } from "next/server"; import { co ...

mongodb does not support this collection option

I'm attempting to establish a new collection in MongoDB, but I am encountering an issue: The 'name' field does not qualify as a valid collection option My MongoDB version is 4.0.0. Here is the code snippet: const MongoClient = require(& ...

Showing the value of a variable in the select dropdown field while editing using React Bootstrap

When it comes to editing, I am using input select. The ant design framework successfully displays the content of the status variable in the input field. However, in the react-bootstrap framework, I am facing issues with displaying the content of the status ...