Using AngularJS to handle form data without ng-model

I am facing a unique situation that may seem a bit strange. I have a form that needs to edit/update information from different objects, such as services.

My goal is to use ng-model to link input fields to their respective objects, but when the form is submitted, I need to convert Angular's Form object into a formData object for POSTing. Has anyone done this before without tedious looping?

HTML

<form name="Ctrl.form" ng-submit="Ctrl.submit()" ng-controller="MyController as Ctrl">
   <input type="text" name="full_name" ng-model="Ctrl.user.fullName">
   <input type="text" name="cart_total" ng-model="Ctrl.cart.gross_total">
   <input type="city" name="city" ng-model="Ctrl.dropship.city">
</form>

Controller

this.user = User.getData();
this.cart = Cart.get();
this.dropship = User.addressBook.getDropShip();

this.submit = function() {
   // transform this.form into formData
}

Does this all make sense? Am I overlooking something?

Thank you! Sincerely

Edit: The form gathers information from multiple objects, but not every property can be POSTed. I hope this clarifies things.

Answer №1

To streamline your form submission process, ensure that the user object is linked to the input fields and then simply pass it to the submit function when needed:

HTML

<form name="Ctrl.form" ng-submit="Ctrl.submit(Ctrl.user)" ng-controller="MyController as Ctrl">
   <input type="text" name="full_name" ng-model="Ctrl.user.fullName">
</form>

Controller

this.user = User.fetchData();
this.submit = function(user) {
     $http({ method:'POST', url: 'AddUser', data: user })
        .success(function() {
             // Handle success response
        });       
}

Answer №2

When passing an object as a parameter to a JavaScript function, it is passed by reference rather than being copied. Therefore, any changes made to the object within the function will affect the original object's address in memory, allowing for reusability of the service across multiple views.

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

Checking User's Admin Permissions with AngularJS Service

I am currently working on a SharePoint App with AngularJS and I have created a service to determine whether the user is an Admin or not. The service is functioning correctly, but I'm unsure how to integrate it into a controller. My objective is to hav ...

Send data from an AJAX request to a Laravel controller

Here is the code for my ajax request where I am trying to pass values to a controller in Laravel. var deviceid="<?php echo $id; ?>"; var day="<?php echo $day; ?>"; $.ajax({ 'async': false, 'global': false, url ...

Switch between divs based on the current selection

var header = $("#accordion"); $.each(data, function () { header.append("<a id='Headanchor' href='javascript:toggleDiv($(this));'>" + this.LongName + "</a>" + "<br />", "&l ...

Posting several pictures with Protractor

In my test suite, I have a specific scenario that requires the following steps: Click on a button. Upload an image from a specified directory. Wait for 15 seconds Repeat Steps 1-3 for all images in the specified directory. I need to figure out how to up ...

Avoiding the storage of POST data in JSON format

Here is some code I am working with: var jsonString = "some string of json"; $.post('proxy.php', { data : jsonString }, function(response) { var print = response; alert(print); }); And this P ...

What is the method for selecting a check box in AngularJS?

I am struggling with two lists (List 1 and List 2) of checkboxes that have three items in common. The issue I'm facing is that when I check an item in List 1, the corresponding item in List 2 also gets checked, which should not happen. I need to find ...

Simulating Cordova plugin functionality during unit testing

I have a code snippet that I need to test in my controller: $scope.fbLogin = function() { console.log('Start FB login'); facebookConnectPlugin.login(["public_profile", "email", "user_friends"], FacebookServices.fbLoginSuccess, FacebookServic ...

PhantomJS fails to trigger function within page.evaluate

My current project involves scraping data from a Facebook page using the PhantomJS node module (https://github.com/sgentle/phantomjs-node). However, I am facing an issue where the function I pass to evaluate the page is not being executed. Interestingly, w ...

Learn how to retrieve the value of an associated field at a specific index by utilizing a combo box in JavaScript when receiving a JSON response

Hey there, I'm currently working on a phone-gap app where I need to fetch data from a WCF service that returns JSON responses. Specifically, I want to display the DesignName in a combo box and pass the associated designId. Any thoughts on how I can ac ...

Unable to loop through using ngFor

I have a component that retrieves data from the back-end and groups it accordingly. Below is the code snippet: getRecruitmentAgencyClientPositions(): void { this._recruitmentAgencyClientsService.getRecruitmentAgencyClientPositions(this.recruitmentAge ...

Countdown Clock in JavaScript for Automatic Logout

I am currently working on creating a countdown timer in JavaScript that should decrement the value of a field by one every minute (for example, starting at 20 and then changing to 19, 18, 17, and so on). However, I am facing issues with its functionality ...

Utilizing HTML5/JavaScript to send a text message from a mobile device

I am developing a mobile web application to be downloaded from various markets with a mini web server, capable of running on any operating system such as iOS, Android, Windows8, and more. My goal is to make the application as OS-independent as possible by ...

Error message: Node: TypeError - Attempted to access the 'sort' property of an undefined variable while using findOneAndUpdate() within a find() operation

My code snippet is shown below: var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/school', function(err, db) { if (err) throw err; db.collection('students').find().toArray( ...

Error: Unable to access the 'version' property of null

Having trouble installing any software on my computer, I've attempted various solutions suggested here but none have been successful. $ npm install axios npm ERR! Cannot read property '**version**' of null npm ERR! A complete log of this ru ...

Javascript involved in the process of CSS Background-Images loading after HTML Images

I quickly put together a microsite that is located at . If your internet connection isn't fast or nothing is cached, you may notice that the background-images used for CSS image-text replacement are the last items to load (especially the h1#head with ...

AutoComplete issues a warning in red when the value assigned to the useState hook it is associated with is altered

const [selectedCountry, setSelectedCountry] = useState(); <Autocomplete autoHighlight={true} //required autoSelect={true} id="geo-select-country" options={availableCountries} value={se ...

Navigating Crossroadsjs Routing: A Beginner's Guide

After exploring various resources to understand how crossroads works, I stumbled upon a question on Stack Overflow that resonated with my struggles. However, despite spending hours trying to implement it, nothing seems to be working. The documentation on i ...

Is there a way to transform a six-digit input into a date format using vue/JavaScript?

I've explored various solutions for this issue, but they all seem to be backend-focused. What I need is a Vue/JavaScript method. I have a string containing IDs, with the first 6 digits representing the date of birth and the final 4 digits being a pers ...

Creating a ListView in React Native and utilizing the CloneWithRow method with an object instead of an

When retrieving data from a webservice, I am able to work with JSON arrays without any issues. WebServiceHandler.get('http:/api.local/stock',{},{) .then((val)=>{ this.setState({ dataSource: this.state.dataSou ...

Export multiple variables at once

Within TypeScript, I have Class1 defined in class.ts, along with some functions from helper.ts and variables from variables.ts: For instance, the content of variables.ts is as follows: export const test1 = 'test1'; export const test2 = 0; expor ...