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

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

What changes should I make to my save function in order to handle both saving and editing user information seamlessly?

My goal for the save function is to achieve two tasks: 1. Save user in table - Completed 2. Update user in table - In progress Save function snippet: var buildUser = function () { $('#save').click(function () { var newUser = {}; ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...

Tips for creating a Vue component that triggers the select dropdown to open when the entire div or wrapper is clicked

I have a custom-designed select dropdown with unique symbols for the select arrow. To achieve this look, I've hidden the default select arrow/triangle and placed our symbol on top as an image file. <div class="select-wrapper"> < ...

Disabling a specific dropdown within ng-repeat in AngularJS

I've encountered a problem with the ng-repeat in my HTML code: <div ng-repeat="a in items"> <div> <span>{{a.name}}</span> </div> <div> <select ng-model="a.c_id" ng-options="d.c_id as d.description ...

ACTUAL preventing a component from losing its focus

I have been exploring ways to effectively stop a DOM element from losing focus. While researching, I came across different solutions on StackOverflow such as: StackOverflow solution 1 StackOverflow solution 2 StackOverflow solution 3 However, these sol ...

Are you ensuring compliance with licensing in your Webpack bundles?

Can webpack be used to verify license compliance? I'm looking for a way to ensure that the license headers from all modules built by webpack are included in the final output file. How can we confirm this is happening? Furthermore, I am also intereste ...

Ways to ensure that v-model does not become "true" or "false" in an input checkbox using Vue

I am currently working on a filter popup that includes a list of checkboxes. By default, some items should be selected and others not selected. I have connected these checkboxes to an object array using v-model. My issue is that when I deselect and select ...

What is the process for activating focus on an input element within a mat-select component?

How can I activate the cursor on the HTML input element (search field) using a keyboard inside mat-select? It functions properly when using a mouse, but in order to meet WCAG requirements, it needs to be fully functional with keyboard navigation. Click h ...

How to resolve: Preventing Ajax - Post request from executing repetitively

I am facing an issue with a table that is formatted using the Datatables script. There is a column in the table which contains icons for actions. When a user clicks on an icon, a modal is loaded and its content is fetched using the POST method. The modal ...

Get a URL from the JSON data returned by the Wikipedia API

How can I retrieve the image URL from a JSON response and store it in a variable? I found helpful information on the MediaWiki API help page Following this example to extract image information from a page: https://commons.wikimedia.org/w/api.php?action= ...

The value is not getting set after calling React Hook UseState

I am currently working on a React component that handles payment processing. There is a part of my code where I utilize the useEffect hook alongside useState to set certain values. Check out the code snippet below: React.useEffect(()=>{ axiosFetch ...

Only Chrome causing my JavaScript execution to freeze due to Ajax

When using Ajax, it is supposed to be asynchronous, but for some reason, it seems like it's either stopping or pausing my JavaScript execution and only resuming once the response is received. Here is an example of HTML value: <input value="foo" d ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...

Utilize jQuery method in HTML to perform parsing operation

Is it possible to invoke my jQuery function from within my HTML code? Here is the code snippet: HTML section: <td style="text-align:left;" align="left" > <div id="bulletin-timestamp" > doTimeStamp(${bulletinTimeStamp[status.index ...

Attach the element to the bottom of the viewport without obstructing the rest of the page

My challenge is to create a button that sticks to the bottom of the viewport and is wider than its parent element. This image illustrates what I am trying to achieve: https://i.stack.imgur.com/rJVvJ.png The issue arises when the viewport height is shorte ...

Tips for avoiding automatic updates to .js scripts after pressing F5

Is there a method to stop a JavaScript script from resetting when the user refreshes the page? For instance, if I have a picture slider that is constantly changing images, I would like the script to continue where it left off instead of starting over wit ...

Google Locations API + React JS + Node.js data not returning

I would like to express my gratitude in advance for any assistance provided. I am currently exploring the development of an application using data from the Google Places web services API. I am utilizing AngularJS, PHP, and HTML for this project. Unfortunat ...

Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray. Below is the code snippet I have in editfrom.TS : // Initialising FormArray valueIngrident = new FormArray([]); constructor(private brandService: BrandService, private PValueInfoSe ...

Struggling to retrieve form data in Node.js, Express, and MongoDB?

How can I properly access the data submitted through a form using Node and Express, in order to store it in MongoDB? When I try to retrieve the NAME field, I get "undefined", and for DATA I get "[object Object]". In my MongoDB database, the _id is genera ...