Angular is known for sending only the fields that have changed to the update method

I need help with optimizing my save method. When a user clicks SAVE, I only want to send the fields that have been changed instead of all 50+ fields on the page. This will reduce the amount of data being sent every time.

Api.Admin.update({
    obsoleteDate : AdminEdit.ObsoleteDate.$dirty== true?$scope.editObsoleteDate:""      
});

In the code above, I am checking if the field's dirty value is true or false. However, I don't want to send an empty value if the field has not been changed. Is there a better way to handle this?

Answer №1

When updating an object, I typically create a new object with only the changed properties and send that object. Before making any changes to the original object, I make a copy of it for comparison purposes. This can easily be adapted to use $dirty in the following way:

function generateUpdateObject(original, current) {
    var modifications = {};

    for (var property in original) {
        if (property.indexOf("$") != 0 && original[property] !== current[property]) {
            modifications[property] = current[property];
        }
    }
    return modifications;
};

My update function then utilizes this method to obtain a fresh object containing only the modifications, assigns the primary key from the current object being manipulated, and sends it to the server. Depending on your backend setup, you may need to perform an http patch request for this process to succeed. Here is a potential implementation:

function saveChanges() {
    var modifications = generateUpdateObject(vm.original, vm.current)
    modifications.id = vm.original.id
    $http.patch("http:/serviceURI.com (" + modifications.id + ")", modifications).then(...)
}

This code snippet was extracted from an application that leverages oData and has been slightly adjusted for this explanation. It forms part of a service that I utilize for all my oData interactions.

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

Change the size of the font with a slider in VueJS

I have been utilizing the project found at This particular project allows end-users to reuse Vue components as editable sections by providing a styler overlay for adjusting content within a div or section. After installation, I added a slider which now ap ...

Achieving functionality with dropdown menus in jQuery

I am facing an issue with a dropdown menu that works perfectly in jsFiddle during testing, but does not function as expected when I run it on my testing server. jsFiddle: http://jsfiddle.net/cyberjo50/39bu8/2/ HTML <!doctype html> <html> < ...

ReactJs CSS - This file type requires a specific loader for processing. There are currently no loaders configured to handle this file

I've noticed that this issue has been raised multiple times before. Despite going through all the questions, I still can't seem to resolve it. The transition from Typescript to Javascript went smoothly until I reached the implementation of CSS. U ...

Utilizing local JSON data with Morris.js: A beginner's guide

I am working on dynamically plotting a Morris line using data from a local file called sales.php (in json format): [ { year: '2008', value: 20 }, { year: '2009', value: 10 }, { year: '2010', value: 5 }, { year: ' ...

NodeJs simple mock: Capturing query string parameters with ease

I'm currently developing a basic mock server using only JavaScript and Yarn. Simply put, I have this functional code snippet: function server() { (...) return { users: generate(userGenerator, 150) } This piece of code successfully generates 15 ...

Developing a personalized error message pop-up system in Electron

I am currently in the process of developing an application for file backup, which involves a lot of reading and writing to the filesystem. While most parts of the app are functioning well, I am facing some challenges with error handling. In the image belo ...

Tips for making nested sliding divs within a parent sliding div

Is it possible to slide a float type div inside another div like this example, but with a white box containing "apple" text sliding inside the black div it's in? I have attempted to recreate the effect using this example. Here is my current JavaScript ...

Using a physical Android device to test and run a Meteor mobile application

I'm struggling to get my Meteor app to run on my Android device (LG G2). Despite searching online for a solution, I haven't come across any similar issues. I followed the instructions carefully, added the Android platform to my project, and ran i ...

Combine the jQuery selectors :has() and :contains() for effective element targeting!

I am trying to select a list item element that has a label element inside it. My goal is to use the :has() selector to target the list item and then match text within the label using the :contains() selector. Can I achieve this in a single line of jQuery ...

`Moving smoothly with a slider and then reversing direction`

I have implemented a range slider to control the value in an input field. The values can vary greatly, so I needed finer control for lower numbers that gradually expands for larger numbers. To address this issue, I utilized an easing equation based on the ...

Solution: The issue where the children's onChange event was not updating the parent in Ant Design was discovered to be due to the Select and Table components nested inside a Tab not changing according to the pageSize

I'm facing an issue with updating a parent element when the children's onChange event is triggered. Specifically, I have an Ant Design Select and Table inside a Tab that are not reflecting changes in the pageSize value. Although setPageSize func ...

Navigating to a new page by selecting a row in a material-ui table

Within my project, there is a file labeled route-names.js containing the following entry: export const REVIEW_FORM_URL = '/custom-forms/:customFormId'; In one of my material-ui tables with multiple rows, clicking on a row reveals the id as ...

Show User-Specific Information Using DataTable

After conducting extensive research, I have been unable to find a suitable example to reference. My goal is to customize my DataTable so that it only displays data relevant to the currently logged-in user (admin accounts will have access to all data). I am ...

The most convenient method for automatically updating Google Charts embedded on a webpage

I am facing an issue with refreshing a Google Graph that displays data from a MySQL database. The graph is being drawn within a webpage along with other metrics: Data Output from grab_twitter_stats.php: [15, 32], [14, 55], [13, 45], [12, 52], [11, 57], [ ...

Manipulating the DOM with AngularJs directives

I have a custom directive that displays a list of Users with their names as clickable links. Within the template of this directive, I am using the following loop: <ng-repeat="user in myctrl.users /> <a href="" >{{user.name}}</a> No ...

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

Perform Action Only When Clicking "X" Button on JQuery Dialog

I have a dialog box with two buttons, "Yes" and "No", which trigger different functions when clicked. $('#divDialog').dialog({ modal:true, width:450, resizable: false, buttons: [{ text: 'Yes', ...

Checking for at least one matching pair in a JavaScript object

I have a pair of dictionaries that I need to compare in JavaScript. The goal is to determine if there is at least one identical key-value pair between them, not necessarily the entire dictionary being identical. my_dict = {"Text1":"Text1", "Text2":"Text3", ...

Find a way to incorporate social media features into a web application that functions intermittently

Currently, I am in the process of developing a social media app and working on integrating a search feature to enable users to find friends. The code I have below seems to be functional at times but not consistent (quite frustrating!) The issue seems to st ...

Tips for storing and retrieving high scores in a JavaScript game

I've just finished creating a JavaScript snake game and now I'd like to add a "scores" option that displays the top 10 players along with their names and scores. My initial plan was to create an object containing the player's name and score ...