What is the best way to submit updated data from an Angular form?

Currently, I have a situation where multiple forms are connected to a backend service for storing data.

My query is whether there exists a typical angular method to identify which properties of the model have been altered and only send those in the POST request. As of now, all data is being sent even if no changes have been made.

Answer №1

When considering the question at hand, there are two potential scenarios to address.

  1. If a user fills out the fields and clicks on the SAVE button, a PATCH request will be sent to save/update the values.

  2. As the user makes changes to the values, a request must be triggered.

Regarding the first scenario:

To keep track of any changes made, it is suggested to maintain a hashmap. Utilize the ng-modal directive for all user input fields. Let's take, for example, two input fields: username and password.

<input type="text" ng-modal="username" />
<input type="password" ng-modal="password" />

In your controller:

$scope.userInfo = {
  user: $scope.username,
  pass: $scope.password
};

Any changes will automatically reflect in your views and models through two-way binding.

Now, you can compare the old and new values to determine which ones to send as needed.

For the second scenario:

Utilize Angular's watchCollection function.

scope.$watchCollection('[username, password]', function () {
  // initiate a request
});

EDIT

It is possible to use a debounce method for the second approach.

// Returns a function that, when continuously invoked, won't trigger repeatedly unless specified time has passed.
_.debounce = function(func, wait, immediate) {
  var timeout, args, context, timestamp, result;

  var later = function() {
    var last = _.now() - timestamp;

    if (last < wait && last >= 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function() {
    context = this;
    args = arguments;
    timestamp = _.now();
    var callNow = immediate && !timeout;
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
};

Source: https://github.com/jashkenas/underscore/blob/master/underscore.js

Answer №2

There isn't a one-size-fits-all method for this. Here's another approach that doesn't involve using watchers. By passing 'form' as an argument in the update function, you can identify which controls have been modified.

Check out this example on Plunker

.controller('ExampleController', ['$scope', function($scope) {
  $scope.user = {}
  var formFields = ['firstName', 'lastName'];

  $scope.update = function(form, user) {
    $scope.updatedFields = {};
    angular.forEach(formFields, function(field) {
      if (form[field].$dirty) {
        $scope.updatedFields[field] = $scope.user[field];
        // Reset field to pristine state temporarily (demo purpose only)
        form[field].$dirty = false;
      }
    });
  };
}]);

You can use the same string for both input name and model.

 <input type="text" ng-model="user.firstName" name="firstName"/>

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

How important is it to maintain synchronization with $inject?

Currently diving into the Angular documentation regarding dependency injection, I'm pondering over the concept of staying 'in sync'. In essence, what distinguishes keeping things 'in sync' from maintaining them 'in the same o ...

Learn how to import MarkerClusterer from the React Google Maps library without using the require method

The sample provided utilizes const { MarkerClusterer } = require("react-google-maps/lib/components/addons/MarkerClusterer");, however, I would prefer to use the import method. I attempted using: import { MarkerClusterer } from 'react-google-maps/lib ...

How to dynamically populate a select option with data from a database in CodeIgniter 3 and automatically display the result in a text

How can I fetch select options from a database in CodeIgniter 3 and display the result in a text field and span area? Currently, I am only able to display data from the row_name when an option is selected. Here is my current implementation: <?php $query ...

Unable to successfully download npm packages - encountered an error running `[email protected] install: `node-pre-gyp install --fallback-to-build` on Ubuntu 18.04 system

I am facing an issue while trying to npm install (using lerna bootstrap) a project on Ubuntu 18.04. The error I encounter is related to node-pre-gyp install --fallback-to-build. I have attempted installing node-gyp, node-pre-gyp, and apt-get build-essenti ...

Resetting values in Javascript and JQuery when clicking a button

I've recently implemented a feature on my website header where clicking on the search button reveals a search bar, and clicking on the account button reveals an account bar. With some valuable assistance from Madalin, I was able to achieve this functi ...

Displaying a loading spinner using JQuery while content is being loaded into a div

I have a navigation bar with links that load content from corresponding HTML pages into a div next to the navigation bar when clicked. To make it more user-friendly, I want to display a spinner while the content is loading. However, the current code I trie ...

Using an xmlhttprequest to retrieve a PDF file functions properly in synchronous mode, but encounters issues in

Today I'm experimenting with some code that scrapes PDFs from a chrome extension by detecting user-clicked links. I've noticed that synchronous xmlhttprequests work perfectly for both HTML documents and PDFs. However, I seem to be facing an issue ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...

What could be causing the Universal Code for Disqus to not function properly?

Struggling to get this code to work on my website. I've tried everything, from clearing caches and cookies to disabling plugins and extensions, but still no luck. Check out the code below: import React, { Component } from 'react' import { ...

What is the best way to customize material components using styled components?

What is the best approach to override material components with styled components, considering that material-ui component classes typically have higher priority than styled-component classes? Is using the !important flag the most effective solution? <bu ...

A guide on incorporating user input and output in Javascript using React and Material UI

Currently, I am working on a project that requires ReactJS and Material UI. My main goal is to implement the code provided below in just a single JS file. Is there a way to modify this code to meet my formatting requirements? //js file function calculat ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

How can I extract the value from the object returned by an AJAX call?

HTML file <div class="container"> <table id="headerTable" class="table table-bordered"> <thead> <tr> <th colspan="2">Header</th> </tr> </thead> <tbody> <c:forEach item ...

Localization for Timeago JS Plugin

Currently, I have integrated the jQuery TimeAgo plugin into my project and included the following code snippet for localization in Portuguese: // Portuguese jQuery.timeago.settings.strings = { suffixAgo: "atrás", suffixFromNow: "a partir de agora", ...

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

Leveraging Javascript to generate universal HTML content for various Javascript files

Present Situation: I have a timesheet feature that enables users to input their leave, TOIL, and sick days along with the respective hours. Additionally, there is a table that dynamically adds a new row every time the plus button is clicked using the foll ...

Convert a relative path to an absolute path using the file:// protocol

When I scrape a website with similar html content, I come across the following code: <a href="/pages/1></a> In addition to this, I have access to the window.location object which contains: origin:"http://www.example.org" This allows me to ...

Imagine a complex JSON structure with multiple levels of nesting

Take a look at this JSON data : { department_1 : [{ id : 1, name = Joe Smith, email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660c150b0f120e2613150048030213">[email protected]</a>}, ...., { id : 500, name ...

Transform jQuery code to its equivalent in vanilla JavaScript

While I am proficient in using jQuery, my knowledge of pure JavaScript is somewhat limited. Below is the jQuery code that I have been working with: $(document).ready(function() { $.get('http://jsonip.com/', function(r){ var ip_addre ...

How to extract column name from query result set using JavaScript in Snowflake database?

When querying in Snowflake with JavaScript inside a stored procedure, we typically receive a Result_set. How can the column names of the output result be retrieved using the JavaScript API? Please note that this inquiry is not about retrieving the values ...