Exploring Angular.js: How to propagate model changes from a child controller within an ng-repeat loop?

I'm facing an issue in my Angular application where changes made to data inside a child controller's form are not being reflected back in the parent array after saving using Restangular. I have tried using debounce to auto-save the data, but it seems that methods like `angular.copy` and `Restangular.copy` are not behaving as expected. Additionally, manually setting the item to the correct index in the array causes the cursor to lose focus in the input field.

Below is a simplified version of the child controller's code. To see the full example, you can check out this JS Bin. Is there a different approach that could be used to address this issue?

$scope.personCopy = angular.copy($scope.person);

// Debounce and auto-save changes
$scope.$watch('personCopy', function(newVal, oldVal) {
  if (newVal && newVal != oldVal) {
    if (timeout) $timeout.cancel(timeout);
    timeout = $timeout(savePerson, 1000);
  }
}, true);

var savePerson = function() {
  // (In my real app, the following is inside a save callback)
  // Method 1: (doesn't work at all)
  $scope.person = $scope.personCopy
  // Method 2: (works with angular.copy, but not Restangular.copy)
  // angular.copy($scope.personCopy, $scope.person);
  // Method 3: (works, but cursor loses focus)
  // $scope.people[$scope.$index] = $scope.personCopy;
};

Answer №1

If you want Method 3 to be effective for you, make sure to include "track by" in your ng-repeat:

<li ng-repeat='person in people track by $index' ng-controller='EditPersonController'>

Check out this working example: http://jsbin.com/jitujaro/3/edit

The issue with losing focus is due to the fact that the DOM for that ngRepeat is constantly being re-created each time you update people. By using track by, Angular understands that there is no need to recreate those DOM elements.

The reason why methods 1 and 2 are not successful has to do with Javascript's prototypal inheritance. When updating a variable located on a parent scope, a new local copy of that variable is created in the local scope. However, when updating a property of an object located on a parent scope (as done in method 3), the update takes place on the parent object as intended.

Answer №2

Experiment with

angular.merge($scope.user, $scope.originalUser);

as opposed to

$scope.user = $scope.originalUser;

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

Transitioning from a multipage application to Piral: A comprehensive guide

Our organization operates several ASP.NET Core applications that are traditional multipage applications. As we develop a new portal using Piral, we want to incorporate elements from our existing applications while also introducing new modules. How can we ...

What is the best way to include several IDs in a discord.js verification process?

I am attempting to create a basic script that verifies if the user's ID matches the one specified in the code. However, I'm struggling to understand how to achieve this. Any assistance from you all would be greatly appreciated. if(message.autho ...

Instructions for subtracting the value of a cell in column 22 from a cell in column 24 within the same row when a change trigger occurs utilizing Google Apps Script

I need help modifying the script below to only subtract the row on which the change is made, instead of subtracting all rows in the sheet when the on-change trigger executes. var sourceSpreadsheetID = '1r4e4BNKwsmdC2Ry93Mq-N49zj3DAZVpHG21TgTe0FWY&a ...

Retrieve the value from a variable located outside an API function call

As I work on developing a chat application project that includes abusive text detection, I have encountered an issue with accessing data from the Perspective API. While I am able to set attributes within the API function, I face challenges accessing them o ...

The success callback method is no longer correctly referencing the variable due to a change in the AJAX request

Imagine you have a table in your HTML file with the following rows, where {{ }} represent variables: <tr id="{{ object.id }}"> <td class="name">{{ object.name }}</td> </tr> <tr id="{{ object.id }}"> <td class="nam ...

The empty string is not getting recognized as part of an array

Currently, I have a textarea field where pressing enter submits and creates a new item in the array. Pressing shift + enter creates a new line in the textarea input field. But when trying to submit by pressing shift and enter after creating a new line, it ...

What is the best way to access nested JSON data in Vue.js code demonstrated here?

How can I properly access the nested JSON data for stage.name provided in the example below? As shown in the template, my attempt to retrieve the stage name is not working. Using vue.js created() { url="http://{{ api_endpoint }}" fetch(url) ...

Directives causing disruption to one another

Two directives are at the same level in my code: function signUpForm(djangoAuth, Validate){ return{ restrict:'A', controller:["$rootScope","$scope",function($rootScope, $scope){ $scope.submitFunction = function(formData){ ...

Is it possible to group an array of objects by a specific element?

Take a look at this example: JsFiddle Query: I'm dealing with the following JSON Array y= [ {"LngTrend":15,"DblValue":10,"DtmStamp":1358226000000}, {"LngTrend":16,"DblValue":92,"DtmStamp":1358226000000}, {"LngTrend":17,"DblValue":45,"DtmSta ...

Failed to insert a new element into the MongoDB array

After trying the code below to update a document within a collection, I encountered an issue where a new item was not being added to an array in the script. Despite no exceptions being thrown, the array remained unchanged. I am seeking advice from experts ...

Converting Axios URL Parameter to Array of Strings in ExpressJS

How to Send a GET Request using axios: await this.client.get('/endpoint', { params: { query: ['max', 'kevin'] } }) This will result in a URL that looks like this: Request GET /endpoint?query[]=max&query[]=kevin Any sugge ...

Utilizing route parameters in AngularJS $routeProvider resolve function

I'm having trouble using a route parameter in the resolve method of a $routeProvider route. Take a look at my code: .when('/agency/edit/:agencyId', { controller: 'agencyController', templateUrl: baseUrl + 'Content/tem ...

Utilizing ng-style with a ForEach loop on an Object

How can I dynamically add a new style property to objects in an array in Angular, and then use that property inside ng-style? CommentService.GetComments(12535372).then(function () { $scope.comments = CommentService.data(); angular.forEac ...

Clever method for enabling image uploads upon image selection without needing to click an upload button using JQuery

Is there a way to automatically upload the file without having to click the upload button? Detail : The code below shows an input field for uploading an image, where you have to select the file and then click the "Upload" button to actually upload it: & ...

Typing should be positioned on either side of the declaration

When I define the type MyType, it looks like this: export type MyType = { ID: string, Name?: string }; Now, I have the option to declare a variable named myVar using three slightly different syntaxes: By placing MyType next to the variable ...

Aggregate the data entered into input fields on one page and display them on a separate page

Can you help me with this task? - I have 2 pages set up (page 1 has input fields & page 2 is where the entered data should be displayed) - I want to retrieve all the text input from the first field and insert it into the "content" tag on the second page. ...

Adding functions to the prototype of a function in JavaScript

Is there a more concise way to simplify this code snippet? var controller = function(){ /*--- constructor ---*/ }; controller.prototype.function1 = function(){ //Prototype method1 } controller.prototype.function2 = function(){ //Prototyp ...

Angular dropdown menu with 2 options

Looking to implement a select box with various price ranges to choose from. For example: - 0 to $2,000 - $2,000 to $3,500 - $3,500 to $5,000 - $5,000 to $7,500 - $7,500 to $10,000 - $10,000 Once a user selects an option, I want to automatically set the ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

The class "pagination pagination-lg" from the link https://angular-ui.github.io/bootstrap/#/pagination seems to be malfunctioning in Bootstrap 4

Just starting out with angularjs and I'm trying to implement pagination using https://angular-ui.github.io/bootstrap/#/pagination. However, I'm facing an issue where the style class "pagination pagination-lg" is not applying properly. I'm cu ...