Trouble with JSON array in $http service

As a newcomer to Angular, I am facing an issue in my application where nested ng-repeat is causing problems when submitting the form to hit the rest API using $http. When normal data is submitted, it works fine but not with nested ng-repeat fields upon clicking the save button. Below is the code snippet with more details. The entire data should be displayed in the console. I suspect there might be a mistake somewhere. Your help would be greatly appreciated.

JS Code:

 $scope.saveVenFormData = function(vendet){
     console.log($scope.vendet);
     $scope.venFullAddress.push({
        'vendorName': $scope.name,
        'panNum': $scope.panNum,
        'personName': $scope.venBusDetails.personName,
        'mobileNum': $scope.venBusDetails.mobileNum,
        'workNum': $scope.workNum,
        'emailid': $scope.emailid,
        'addressLine1': $scope.addressLine1,
        'addressLine2': $scope.addressLine2,
        'city': $scope.city,
        'state': $scope.state
      });
     var dataObj = $scope.venFullAddress;

     $http.get('/showVendors').success(function(data){
        console.log(angular.toJson(data));
     });

     var res = $http.post('http://localhost:8080/dman/mm', dataObj);

     res.success(function(data, status, headers, config) {
        $scope.message = data;
     });

     res.error(function(data, status, headers, config) {
        alert( "failure message: " + JSON.stringify({data: data}));
     }); 
   };
   

JSON Structure:

{
     "vendor": {
       "vendorName": "",
          "panNum": "",
          "venBusDetails": [{
              "personName": "",
              "mobileNum": "",
              "workNum": "",
              "emailid": "",
              "venContDetails": [{
                  "addressLine1": "",
                  "addressLine2": "",
                  "city": "",
                  "state": ""
                }]
            }]
        }
      } 
    

Link to Plunker for reference. To simplify things, I have provided a json structure above. My goal is to retrieve all the data from the form and send it to the rest API. Kindly check the link provided. Thank you.

Answer №1

Give this a try

$scope.dataObjToSubmit = {
  "vendor": {
    "vendorName": $scope.vendorInfo.vendorName,
    "panNumber": $scope.vendorInfo.panNum,
    "businessDetails": [{
      "contactPerson": $scope.businessDetails[0].personName,
      "mobileNumber": $scope.businessDetails[0].mobileNum,
      "workNumber": $scope.businessDetails[0].workNum,
      "email": $scope.businessDetails[0].emailid,
      "contactDetails": [{
        "addressLine1": $scope.contactDetails[0].addressLine1,
        "addressLine2": $scope.contactDetails[0].addressLine2,
        "city": $scope.contactDetails[0].city,
        "state": $scope.contactDetails[0].state
      }]
    }]
  }
} //Make sure to send this data when using the POST method

You have referenced $scope.name in your JS file, but in the HTML view you are using ng-model="vendorInfo.vendorName". This inconsistency is causing it to always be undefined.

CLICK HERE FOR UPDATED Plunk LINK

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

Does an Angular Js service return a function or an object?

According to the documentation provided by Angular JS here The service function takes two arguments: name: name constructor: An injectable class (constructor function) that will be instantiated. Internally : { $get: function() { return $injecto ...

Deleting elements from arrayA that do not exist in arrayB using JavaScript

Seeking guidance on a small project of mine. For example, I have these two arrays: chosenItems = ['apple', 'banana', 'cherry', 'date', 'kiwi'] availableFruits = ['apple', 'cherry', &ap ...

Postponing the initial display of a webpage

I am working with a web application from a different company that has some customization options limited to CSS and allows me to add HTML content at certain points in the code. However, I need more flexibility than what CSS can offer, so I have resorted t ...

JSON parser made easy

Greetings! I am currently facing an issue with a JSON simple parser. I need to parse data that looks like this {"phoneNumber":"9874662222","name":"Иван","surname":"Иванов","key":"ivanov0"}{"phoneNumber":"9874662222","name":"Иван","surname":" ...

Sticky positioning is not maintaining its position at the top

I've noticed a strange behavior where, when I scroll down, the yellow box goes on top of the blue box. I have set both boxes to have a position sticky so that they should stay in place and not overlap. However, I want only the orange box to be scrolla ...

Capturing information from a modifiable table using Javascript

Creating an HTML Editable table with the property CONTENTEDITABLE, each TD has a unique ID (even though it's a long process and I only have basic JS knowledge) to keep track of the information inside. The table is wrapped by a form. At the end of the ...

How to display output from a component in card format

Screen shot having difficulty retrieving JSON data from this URL in order to display the time, hash, and height data as individual cards I managed to successfully showcase JSON data fetched from this source, where everything was displayed neatly as card ...

fetching JSON information from PHP script in an Android mobile app

As a novice in android app development, I recently attempted to connect my application to a server to retrieve data from MySQL. My initial focus was on creating the login functionality, but encountered challenges with reading JSON data using my code. Here ...

Challenges with Json deserializing String arrays in C# Entity Framework

I am encountering an issue with deserializing a Json file to Entity framework. To simplify, let's assume the Json structure looks like this: { "stat": "val0", "results": [ { "datasets": [ "val1", "val2" ], "h ...

Add an item to a sub-array within an object stored in a Mongoose array

Here is the schema I am working with: { ..., description: { type: String, required: true, trim: true }, tags: { type: [{ type: String }] }, lessons: [{ name: String, ...

Searching by element within a JSON array

I've tried various solutions from different sources but haven't been able to find the correct answer yet. create table mstore ( muuid uuid PRIMARY KEY, msid text, m_json JSONb[] not NULL ); Inserted the first row: insert into mstore (muuid, msid ...

What is the method for extracting the text from the currently chosen option?

const desiredOption = x.match(/<option selected="selected" value='[^']*'>([^<]*)<\/option>/)[1]; What is the best way to extract the text content from the selected option in the given string? ...

While attempting to deploy on Vercel, I encountered an error while constructing my Next.js project

While working on my Next login signup project, I encountered the following error: WagmiProviderNotFoundError: `useConfig` must be used within `WagmiProvider`. The documentation for this issue can be found <a href="https://wagmi.sh/react/api/WagmiProvide ...

What does Event.target.id return - the HTML id value or the HTML name value?

HTML Form Example: <form id="form-product-add" style="display: inline;"> <input name="csrf" type="hidden" value="<?= $this->csrf; ?>"> <input type="hidden" name="a ...

Using a Json file as a data provider for TestNG tests

I have a JSON structure provided below: I need to develop a Java method that takes only the SuperParent as an input parameter and returns "Registration Data" and "Registration Data1" along with their child elements as a TestNG data provider object. "Super ...

Unveiling the secrets to integrating infinite scrolling in a listview

In the process of developing an application, I have incorporated Json parsing to parse data and displayed it in a listview. The response includes objects such as totalpage and current page. Initially, a new user will only see items from the first page. Ho ...

I'm currently attempting to create a dynamic object using code, but it doesn't seem to be functioning as expected. I'm curious about what might be causing the issue

I am brand new to exploring JavaScript, HTML, and CSS. I've gone through my code several times but can't quite pinpoint what's causing it not to function properly. While there are no apparent errors being returned, the expected behavior is n ...

Having trouble making the JavaScript mouseenter function work properly?

Hi there, I'm having trouble with this code and I can't figure out why it's not working. $('#thumbs > li').mouseenter(function() { $(this).find("div").fadeIn(); }).mouseleave(function(){ $(this).find("div").fadeOut(); ...

Using jQuery to gradually fade out my sidebar (div)

I have written the following code to hide my sidebar when the screen width is less than 1024 pixels, but it doesn't seem to be working. It worked fine on a previous website, so I'm not sure what the issue is here. Any help would be greatly apprec ...

AngularJS encountered an incorrect injection token, specifically an unexpected function instead of the expected service name as a string

I am fairly new to working with AngularJS and I'm having trouble adding a new feature to the app, specifically uploading attachments to a server folder. Whenever I try to implement the function following the "requisition" parameter in the controller, ...