Issue with RestAngular: The put and customPUT methods are sending the outdated object instead of the updated one

Every time I use the put or customPUT method and inspect the request body in the browser, it always sends the original object instead of the updated one. Interestingly, when I check the RestAngular object with a {{ object }}, it clearly shows that it is being updated.

Take a look at the following controller (where APIUsers represents a RestAngular Service):

$scope.objects = {};
(function waitForNgInit(fnct) {
    $scope.$watch('userID', function(newVal) {
        if (newVal !== undefined) {
            fnct();
        }
    });
})(function retrieveUser() {
    $scope.objects.user = APIUsers.one($scope.userID).get().$object;
});

$scope.saveSettings = function() {
    $scope.objects.user.customPUT($scope.objects.user).then(function(resp) {
        $scope.errors = [];
    }, function(err) {
        console.log(err.data);
        $scope.errors = err.data.errors;
    });
};

And here is the Jade (HTML Template Code):

div.user-settings.form-section(ng-controller="userSettingsFormController")
    {{ objects }}
    ul.error-box(ng-show="errors != undefined && errors.legnth != 0")
        li(ng-repeat="error in errors") {{ error.msg }}
    .form-group
        label(for="username") Username
        input(type="textfield" ng-model="objects.user.username")
    .form-group
        label(for="username") Email
        input(type="textfield" ng-model="objects.user.email")
    .form-group
        label(for="username") Profile Picture
        input(type="file" ng-model="objects.user.profilePicture")
    span.submit-button(ng-click="saveSettings()") Save Changes

Answer №1

This Restangular bug has been around for a while and is well-documented. You can find more information about it here.

While they are in the process of fixing it, you can use the following code to make it work temporarily:

$scope.submit = function submit() {
    Restangular
      .copy($scope.ledger)
      .save()
      .then(function () {
        growl.success(gettext('Updated successfully.'));
      });
  };

Answer №2

Dealing with a similar issue, it seems like allowing the digest cycle to finish is key for the restangular object to update properly.

You might want to consider using $timeout to wrap your put() method:

$timeout(function () {
  $scope.objects.user.customPUT($scope.objects.user).then(function(resp) {
    $scope.errors = [];
  }, function(err) {
    console.log(err.data);
    $scope.errors = err.data.errors;
  });
});

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

Arranging a javascript object by organizing an array as a value

Looking to organize a JavaScript Object structured as key:pair, where the pair consists of an array with 2 timestamp values. The goal is to arrange the elements so that those with the smallest numbers (earliest times) are shown first. For instance, consid ...

Find the maximum width of an element within a Div that is larger than the widths of the other three elements using jQuery

After implementing a Dialog using JqueryUI, I noticed that inside the dialog there is a <div>. Within this <div>, there are three <button> elements labeled "Delete", "Cancel", and "Ok". Interestingly, the widths of these elements are auto ...

Ways to determine the text field value without the need for a submit button

I need help with a calculation that doesn't require a submit button. I want to automatically calculate and display the total value in a text field based on the weight, height, and number of pieces entered by the user without having to refresh the page ...

Instructions on creating a Superfish menu with a vertical layout in the first level and a horizontal layout in the second level

Currently, I am using the Superfish menu in Drupal7 and have designed my first item level to be vertical. However, I now want to style my second item level horizontally. I have tried various CSS approaches and added some class names via jQuery like $(&apo ...

Can the color of an ion-radio be adjusted when it is not selected?

I am experiencing an issue where I need to change the default color (grey) to a specific color of my choice, such as the primary color. I have attempted the following methods: <ion-col sizeXs="12" sizeMd="6" class="radio-box"> <ion-item line ...

Obtain the API response using a Promise.then() in AngularJS

Recently, I've been delving into AngularJS and trying to create a function that deletes a user. The goal is to have the function return a boolean value indicating whether the deletion was successful or not. Despite my best efforts, the promise always ...

using node.js to extract a cookie from a 302 redirect

Need help simulating a login using node.js. The request is a post method and returns a 302 status code. However, when trying to simulate the request in node, I encounter the following error: Error handling unrejected promise: StatusCodeError: 302 Upon i ...

A Guide on How to Sort and Tally Items in a JSON Data Set containing Numerous Objects using JavaScript

I have recently started learning javascript, and everything was going well until I encountered this issue. I need to reformat a JSON file in the following structure: { firstName: "Joel", lastName: "Munz", total: 154, transaction: "111111", ...

Refresh of posts is not occurring upon removal from the database

I am currently in the process of creating a blog using a MEAN stack, and I have encountered a minor issue. Below is the HTML code I am utilizing to fetch all my posts: index.html: <div ng-repeat="post in posts"> <h2> {{post.title}} ...

Sorting price and date with Vue in Laravel - A beginner's guide

Attempting to sort by price and by date. See the code below. I decided not to use the controller for this sorting. Is it feasible to implement it here? It's somewhat functional, but there are some issues. When selecting price, it doesn't seem to ...

implementing data in a single component using vue.js

I am facing an issue with a component where I need to fetch data using an ajax call. The component is being called correctly and the data is returned in the ajax call, but I am struggling to assign it to the data in the template? <template> < ...

Trouble with AngularJS 1.x: radio buttons not displaying as checked

I am currently enhancing a form to include two sets of radio buttons that toggle panels on and off. The first set allows users to choose between contacting the customer ("Yes") or not ("No"). If "Yes" is selected, then they are prompted to specify whether ...

Unable to get the sublocality dropdown list to cascade properly in asp.net mvc

I am dealing with three dropdown lists. The initial action method for the City dropdown is shown below: public ActionResult Create() { List<SelectListItem> li = new List<SelectListItem>(); li.Add(new Sel ...

Leveraging a node.js file monitoring tool in tandem with JetBrains WebStorm

For the past few weeks, I've been incorporating Prettier into my project workflow and I must say, it's really impressive! Working with JetBrains WebStorm as my preferred IDE, I followed the guidelines provided on the Prettier project site to set ...

Skipping validation while navigating back on SmartWizardIf you need to bypass validation during backward

Looking for assistance with Jquery smartwizard? Check out the link. I want to disable validation when a user clicks on the "Previous" button in any step, except for the first step where the Previous button is disabled by default. Below is my JavaScript co ...

Learning to Use jQuery to Send JSON Requests in Rails

I am attempting to send a JSON post request to a Rails 3 server. Here is the AJAX request I have set up: $.ajax({ type: 'POST',<br> contentType: "application/json",<br> url: url, ...

What is the best way to execute a command after the file system has finished writing to a file?

Below is the code under scrutiny: const scriptFiles = fs.readdirSync(scriptsPath) .filter(file => file.endsWith(".sql")); for (const file of scriptFiles) { var data = fs.readFileSync(`${scriptsPath}/${ ...

Guide to displaying a loading message while performing a synchronous AJAX request in a web browser

Is there a way to display a waiting message during a synchronous AJAX call in the browser? I attempted to use the code below, but even after turning off the web server, the "Saving" message did not appear. After some time, only an error event from the AJA ...

Ways to conceal ng repeat using ng if

My autocomplete feature is set up using ng-repeat to display suggestions and ng-click to change the textbox value. However, I am facing an issue where the suggestion does not disappear when the textbox value is already the same as the suggestion. How can I ...

What are your thoughts on this method for preventing scrolling?

Is there a way to prevent scrolling of the underlying content on a webpage when a modal is displayed? I found this code snippet that achieves that. (http://jsfiddle.net/77P2e/) var $window = $(window), previousScrollTop = 0, scrollLock = false; $window.s ...