AngularJS Form Reverts Back to Original State After API Response

In my code, I am using a Factory with ng.resource:

.factory('company', function($resource){
return $resource(appHelper.apiPath('auth/company/info'), {}, {
    update: {
        method: "PUT"
    }
});
});

When submitting the form in my Controller, everything functions correctly as long as the API gives a positive response. However, if there is an error, the API returns a JSON object with HTTP 200. In my callback function, I validate the response:

$scope.saveCompanyForm = function (company) {
        company.$update(
            function(data) {
                    if(data.status == 'ERROR') {
                        alert("error from API")


                    } else {
                        alert("no error")
                    }
            }, function(error) {
                    alert("error")
    }

The issue arises when the API returns an error and the form gets cleared. Strangely, if the API responds with HTTP 500 or 404, the form does not get cleared. Is there any way to prevent Angular from resetting the form? Thank you.

Answer №1

Prior to the callback, ensure you save the information for later use.

$scope.saveCompanyForm = function (company) {

    var savedCompanyInfo = company;

    company.$update(
        function(data) {
                if(data.status == 'ERROR') {
                    alert("Error from API")
                    company = savedCompanyInfo;

                } else {
                    alert("No errors")
                    company = savedCompanyInfo;
                }
        }, function(error) {
                alert("An error occurred")
                company = savedCompanyInfo;
}

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

Identify any fresh elements incorporated into the DOM following an AJAX call

I'm attempting to showcase a newly added div element within the DOM using AJAX. Through AJAX/PHP, I dynamically inserted some new buttons: <button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index ...

Get hefty files through a WCF service

I am currently working on an application that needs to handle large files, which is why I am utilizing a stream parameter. Here is the service contract: [ServiceContract] public interface IFile { [OperationContract] [WebInvoke(Method = "POST", Ur ...

Displaying the combined total for each date

My goal is to calculate the total for each department without duplicates ( which is currently working ) and display all results based on the selected date. I intend to select a date using md-datepicker and then only display the total task time where the d ...

Building Next.js with a designated maximum number of processes/threads

I've uploaded a fresh Next.js app to the cloud server using npx create-next-app. However, when I try to run the build script, the server throws an error 'pthread-create: Resource temporarily unavailable'. { "name": "next&quo ...

Executing JavaScript code within a class object using ASP-VB

I'm looking to create a function that will show a Javascript-based notification. I already have the code for the notification, but I'm trying to encapsulate it in a class library as a function. However, I am unsure about what to return from the f ...

Extract the selected date from the datepicker and showcase it within a designated div element

I need to retrieve the selected date from a jQuery UI datepicker and show it in two places on the page. Currently, the selected date is displayed in the input field of the datepicker, but I also want to display it within a div tag elsewhere on the page. ...

Need help with setting up active buttons for dynamically added elements in jQuery?

I came across this example on adding a button dynamically using jquery and I have a question regarding it. How can I attach jquery functions to the newly created buttons after clicking on the "insert after" button multiple times? For instance, if I click ...

What is V8's approach to managing dictionaries?

After attending V8 presentations, it became clear to me that it optimizes constructions such as the one below by tagging a type object: function Point(x, y) { this.x = x; this.y = y; } I am curious about what happens if I were to return an object (JS ...

Using Javascript Regex to conceal non-ASCII characters in strings

I'm currently working on masking strings using JavaScript regex. However, I've encountered an issue with non-ascii characters. How would you suggest resolving this problem? Below is the code I've been using: var name = "Üsüaüü Bxbd ...

Safari browser is experiencing issues with the custom file upload script

My custom upload script allows users to easily select images for upload by clicking or dragging them into the designated box. A preview of the chosen image should appear, and this functionality works smoothly in Firefox and Chrome. However, I've encou ...

Sending JSON data two times to the ASP.NET MVC controller via POST request

function onTestComplete(content) { var url = '<%= Url.Action("JsonTest","Organization") %>'; $.post(url, null, function(data) { alert(data["name"]); alert(data["ee"]); }); } <% using (Ajax.BeginForm("JsonTe ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

Group-selection

Is there a way to insert a checkbox in front of the parent1 (optgroup) and have all child options automatically selected when I check the parent optgroup? Here is my code: <select id="offc" name="offc[]" multiple> <option value="">Sele ...

obtain an inner element within a container using the class name in a div

I am attempting to locate a span element with the class of main-tag within a nested div. However, I want to avoid using querySelector due to multiple elements in the HTML file sharing the same class and my preference against using IDs. I realize there mig ...

View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The b ...

Experimenting with Jasmine for testing an AngularJS service without the need for mocks

I am interested in utilizing Jasmine for writing tests (not unit tests) for an AngularJS service that acts as a wrapper for a REST API I developed on my server. The goal is to ensure that the service call reaches the server without requiring any form of mo ...

Displaying two distinct tables utilizing ng-repeat by employing customized directives

I'm facing an issue with a custom directive that generates tables and is appearing twice on my index page. The data for these tables comes from the $scope.globalrows variable. Even though globalrows contains 2 arrays, it always displays the second arr ...

Identifying mobile device model

I'm currently working on a web application focused on image manipulation, including cropping and applying effects like sepia. Is there a library available that can help me detect, whether on the front or back end, the type of device a user is using ( ...

Determine if an object has been submitted in a MEAN / AngularJS application

I am working with an AngularJS frontend and using Express, Node, and MongoDB on the backend. My current setup is as follows: // my data to push to the server $scope.things = [{title:"title", other properties}, {title:"title", other properties}, {titl ...

How can I use JavaScript to retrieve information from a different webpage?

I am trying to extract data from another webpage using JavaScript, jQuery, or Ajax without using PHP. I came across a helpful example on Stack Overflow (link here). However, when I implement these codes in my index.html file, it doesn't seem to work. ...