Retrieve every piece of input information using Angular

Trying to figure out how to post input data with Angular, but struggling to extract the data from the input fields.

Below is the HTML code:

<div ng-controller="Test">
<div class="container">
<div class="col-sm-9 col-sm-offset-2">

    <div class="page-header"><h1>Testing</h1></div>

    <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
        <div class="form-group" ng-class="{'has-error' : userForm.name.$invalid && !userForm.name.$pristine, 'has-success' : userForm.name.$valid }">
            <label>Name</label>
            <input type="text" name="name" class="form-control" ng-model="name" required>
            <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">Invalid name</p>
        </div>

        <div class="form-group" ng-class="{'has-error' : userForm.username.$invalid && !userForm.username.$pristine, 'has-success' : userForm.username.$valid && !userForm.username.$pristine}">
            <label>Username</label>
            <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
            <p ng-show="userForm.username.$error.minlength" class="help-block">Too short</p>
            <p ng-show="userForm.username.$error.maxlength" class="help-block">Too long</p>

        </div>

        <div class="form-group" ng-class="{'has-error' : userForm.email.$invalid && !userForm.email.$pristine, 'has-success' : userForm.email.$valid && !userForm.email.$pristine}">
            <label>Email</label>
            <input type="email" name="email" class="form-control" ng-model="email">
            <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email</p>
        </div>      

        <button type="submit" class="btn btn-primary">Add</button>
    </form>
</div>
</div>
</div>

Here is the controller snippet:

as.controller('Test', function($scope, $http, $rootScope)
    {   

        $scope.submitForm = function(isValid) {
            if(isValid) 
            {   
                $http.post($rootScope.appUrl + '/nao/test', {"data": $scope.userForm})
                .success(function(data, status, headers, config) {
                    console.log(data);
                }).error(function(data, status) {

                });
            }

        };
    });

After clicking the button, a POST request is sent, but the data being transmitted appears as follows:

{"data":{"name":{},"username":{},"email":{}}}

How can I retrieve the data from all input fields? Should I reference userForm in the controller as I currently do?

Answer №1

My recommendation is to start by initializing a new $scope object as empty:

$scope.formData = {};

Each field should be a part of this object:

<input type="text" name="email" class="form-control" ng-model="formData.email" required>

Once all fields are filled out, you will have access to the data in the $scope.formData object.

Check out the example on jsFiddle: http://jsfiddle.net/example_username/123ABC/

Answer №2

If you have ng-model variables within your scope:

$scope.firstName
$scope.lastName
$scope.emailAddress

You can prefix all of these with a user. and then send them via ajax as $scope.user instead of $scope.userDetails

Alternatively,

you could try sending an object that is copied using: angular.copy($scope.userDetails)

Answer №3

To keep your data organized in AngularJS, consider creating a property within your scope called userData. Use this property as the prefix for all your ng-model values, such as userData.SOMETHING. This approach allows you to send all the user data easily by referencing $scope.userData, like so: {info: $scope.userData}.

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

Unable to generate a JSON string from the JavaScript object

I need help converting the object I receive from the server into a JSON file for use in a d3.js chart: data = { "dog ":"5", "cat ":"4", "fish ":"12", } The desired output is: { "name" : "animal", "children" : [ {"name":"dog" ...

The time selector does not appear in the v-date-picker widget

I need help figuring out how to select a time range using v-date-picker on vCalender within my Vuetify project. Despite setting the mode of v-date-picker to dateTime, I am unable to find an option to choose the time along with the date. Is there something ...

An error occurs when attempting to use Socket.io without explicitly returning the index.html file

I want to implement WebSockets without needing to return the index.html file. As someone new to Socket.IO, here's what I've attempted: First, I installed Socket.IO using npm: npm install socket.io --save Then, I created a file called index.js ...

C# - Implementing JavaScript Object manipulation in .NET Core

As I was browsing, I noticed many similar questions from years ago. Let's kick off this discussion with a simple JavaScript example showcasing how easy it is to modify, read, and write properties in objects using this language. Take a look at the cod ...

Issue with AngularJS: Copying and appending with $compile is not functioning properly

Below is the snippet of my angularjs Controller var $tr = angular.element("#parent" + obj.field_id).find("tbody"), $nlast = $tr.find("tr:last"), $clone = angular.copy($nlast); $clone.find(':text').val('' ...

NodeJS API Language Configuration

I'm currently working on integrating the DuckDuckGo Instant Answer Api into my NodeJS application. To do so, I am making a data request from the API using Node Request. var request = require('request'); request('http://api.duckduckgo.c ...

Data input via $_POST method during the submission of a web application is failing to

Having trouble with the login functionality in an EllisLab application framework. The data from the $_POST method is not being stored upon form submission, resulting in an error message. When using var_dump($POST), it shows array(0){}. View Error Screensh ...

Arranging elements in two arrays in either ascending or descending order

Looking to implement sorting functionality for the "fuel.name" value within this array... const orders = [ { "_id":"5d14a31490fb1e0012a3d2d8-1", "orderId":"0JL5ORM0JT-1", "created":"2019-06-27T11:05:56.377Z", "createdDate":"2019-06-2 ...

Tips on how to showcase the current time in the local timezone on Next.js without encountering the error message "Text content does not match server-rendered HTML."

Currently, I am sharpening my Next.js skills by building a blog. My current challenge involves formatting a static ISO time string (which represents the creation time of blog posts) to match the local timezone of the user. <div className='post-time ...

Sending information from the backend to the frontend using Node.js and Express

I am seeking advice on the most effective method for achieving a specific task. In my Node.Js / Express application, there is a point where I need to send data to the backend and receive a certain value back to the front end. Typically, this can be accomp ...

Oops! There seems to be an issue with an invalid character in the literal true value while making a POST request to the API with JSON data. The expected character should be

Can anyone help me solve an issue I am facing while trying to use the POST method to insert data using JSON in JS code? When I attempt the transformation, I receive an error message stating: "ERROR: invalid character ' ' in literal true (e ...

Dragging down on an iPhone screen is a feature supported by the Framework7 Cordova platform

I am currently utilizing Framework7 and Cordova wrapper for my IOS application and I am facing an issue with the dragging effect in my content. Even after attempting to disable the pull-to-refresh effect from the Cordova side, the content remains draggabl ...

Access a designated tab using cbpFWTabs

I am currently using the cbpFWTabs plugin from Tympanus for my tabs (http://tympanus.net/Development/TabStylesInspiration/). However, I am struggling to open a specific tab upon page load. I have attempted to create a show method within the page script, bu ...

I've been working on adding dark mode to my header component, and I decided to use context API to manage it. However, I'm running into issues with

In my root component, RootApp.jsx handles the component tree: import { Suspense } from 'react'; import { HashRouter as Router } from 'react-router-dom'; import { Provider } from 'react-redux'; import store from '@/redux/s ...

Difficulty arises when trying to deploy a React application on a stationary Nginx server

I'm encountering issues trying to deploy my React app on a remote server. My Nginx configuration looks like this: server { listen 80; listen [::]:80; server_name xxx.xxx.x.x; root /var/www/my-site; inde ...

Is there a substitute for AngularJS $watch in Aurelia?

I'm in the process of transitioning my existing Angular.js project to Aurelia.js. Here is an example of what I am trying to accomplish: report.js export class Report { list = []; //TODO listChanged(newList, oldList){ ...

Problem arises with table nth-child selector following the addition of grid-gap

Our current table looks like this: https://i.sstatic.net/eUyBB.png The first row has a background color and the second row is white - which is correct. Now I would like to align the attributes to the right. I added the following code to the table: .table ...

Smooth animation is not being achieved with the Jquery dlmenu

I have implemented a multi-level navigation menu using a demo of the jquery dlmenu plugin v1.0.2. Although most of the functions are working smoothly, the CSS3 menu navigation lacks the fluidity of the jQuery left/right sliding effect. Is there a way to ...

A guide on effectively mocking a Vuex store within the parentComponent of VueJS test-utils

I am currently using Jest in conjunction with vue-test-utils to test the reaction of a child component to an $emit event triggered by the parent component. The VueJS test-utils library offers a parentComponent option that can be utilized when mounting or ...

Avoiding 0 being mistakenly interpreted as undefined while utilizing React Conditional Rendering

I have a React component with the following code in its render function: return ( <div> {rating.score && ( <div>do something</div> )} </div> ); The prop rating.score is of type PropTypes.number. Eve ...