Challenges of modifying a scope object in Angular through reference

I am encountering a challenge when trying to update a reference of an object within my code. Here's the scenario:

function modifyUserDetails(user) {
            $scope.initialUser = user;
            $scope.alteredUser = angular.copy(user);
        }

function ApplyUserChanges(form) {
            if (form.$valid) {
                $scope.initialUser = angular.copy($scope.alteredUser);
            }
        }

So far, everything is functioning as expected. I utilize modifyUserDetails(user) within an ng-repeat="user in users" loop to pass in the user object. When ApplyUserChanges is triggered, the initialUser object is successfully updated.

Initially, I assumed that since $scope.initialUser = user;, updating $scope.initialUser would also result in the user object within the users array getting updated, as I thought they shared the same reference. However, upon inspecting with ng-inspect, I noticed that although $scope.initialUser gets updated, the user within the users array remains unchanged.

Any insights on this behavior would be greatly appreciated.

Answer №1

You must make a change

// When you lose reference to the user object
$scope.originalUser = angular.copy($scope.editUser);

instead, use:

angular.extend($scope.originalUser, $scope.editUser)

Explanation of angular.copy:

var user = {name: 'John', age: 30},
        editUser, originalUser;
originalUser = user;
console.log(originalUser); // => {name: 'John', age: 30}
user === originalUser; // => true
editUser = angular.copy(user);
console.log(editUser); // => {name: 'John', age: 30}
user === editUser; => false
angular.extend(originalUser, editUser);
originalUser === user; // => true;
editUser === angular.copy(editUser); // => false
originalUser = angular.copy(editUser); // you have overwritten the reference to user with reference to new object angular.copy(editUser). Hence you have lost you reference to user.
originalUser === user; // => false;

Simplest form of angular.copy and angular.extend:

function copy(src) {
   var newObject = {};
   Object.keys(src).forEach(function(key) {
       newObject[key] = src[key];
   })
   return newObject;
}

function extend(dst, src) {
   Object.keys(src).forEach(function(key) {
       dst[key] = src[key];
   })
   return dst;
}

// Do not use these functions for real applications, only for explanation

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

The proxy encountered a TypeError when the trap for the property 'set' returned a falsish value

After migrating my code from using es5 class prototype representation to es6 class representation, I encountered an error. This is the comparison of the code before and after migration: ES5 syntax function RoutingScreen (context) { Object.assign(this, ...

Access Vuex Getters in a separate JavaScript file

Within the file /store/user/getters.js: function getLoggedIn (state) { return state.loggedIn } In a different file, router-auth.js, I attempted to access the value (true or false) of getters.getLoggedIn in the following manner: import user from '.. ...

Investigate the CSS display property of an element using JavaScript

Can JavaScript be used to determine if an element's CSS display == block or none? ...

A guide to showcasing JSON data on a webpage using JavaScript

I am currently working on a SOAP WSDL invocation application in MobileFirst. The response I receive from the SOAP WSDL is in JSON format and is stored in the result variable. When trying to access the length of the response using result.length, I encounter ...

Retrieve the initial element from a JSON object to identify errors, without being dependent on its specific key name

Utilizing AngularJS, my JSON call can result in various errors. Currently, I am handling it like this: $scope.errors = object.data.form.ERRORS or $scope.errors = object.data.system.ERRORS However, in the future, 'form' or 'system' ...

Employing Angular.js $http.post in conjunction with Codeigniter WITH CSRF protection activated

Seeking help with Angular.js and CodeIgniter integration in an application with CSRF protection. In jQuery, adding the token is straightforward: $.ajaxSetup({ data: { csrf_token: $("input:hidden[name='csrf_token']").val() } In Angular.js, a ...

Tips for creating a responsive layout to ensure that H2 achieves its optimal font size in a one-line DIV

Is there a way to ensure that an H2 headline fits within the width of a DIV element? I am looking for a solution where the font size of the H2 automatically adjusts to display its full text without overflowing or breaking into a second line inside the DIV ...

Issues with displaying data in Angular ChartJS are troubling users

Currently utilizing Angular 6, my goal is to incorporate a Chart.js line chart. Essentially, I am fetching two arrays from my API: one named weight_data and the other named weight_date, which I then utilize for the chart. After receiving the arrays from t ...

Error: Unable to access 'price' property of undefined - Next.js version 14.0.1

I'm encountering an issue with Next.js where my code is not working as expected. Interestingly, the same code works perfectly fine in other templates. let subTotal = 0 if (selectedProducts?.length) { for (let id of selectedProducts) { ...

Trouble With Ajax Submission in CakePhp: Issue with Form Serialization

In my attempt to utilize ajax for sending an array of objects along with serialized form data, I encountered a problem. The issue arises when I include the array in the ajax data along with the serialized form data. This results in the serialized form data ...

What is the best way to share in a LinkedIn group using JavaScript?

Attempting to share on my group via the JavaScript API is resulting in an error - Access to write groups denied (403 Forbidden). How can I resolve this issue? IN.API.Raw("/groups/" + 10356772 + "/posts?format=json") .method("POST") .body(JSON.stringif ...

Fade out the jQuery message after a brief 2-second pause

In my Rails application, I encountered an issue with a flash message that appears after successfully completing an AJAX action. The message displays "Patient Added" but does not include a way to close it without refreshing the page. To address this, I atte ...

Transform a complex PHP array into JSON format using JavaScript

I have a three-tiered PHP array with both numeric indices and key-value pairs. I would like to convert it to JSON, and reiterate through the object list. How would I do this? The PHP array is called $main_array, and appears as: Array( [0] => Arra ...

Issue with D3: Events not triggering transitions

I am currently working on creating a bar chart using D3 in Angular4. // Enter Phase this.chart.selectAll('.bar') .data(this.barData) .enter() .append('rect') .attr('class', 'bar'); // Update Phase let bars ...

The function generalChannel.send does not exist

I've recently started working on a discord bot and I'm facing an issue with getting it to greet everyone when it's turned on. Using the bot.channels.get method, I am able to locate the channel successfully, but when it comes to sending a mes ...

Tips for creating an expression within ng-if

I am struggling with placing an expression inside ng-if that needs to be assessed in order for my content to be shown based on its outcome. This is what I currently have: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image< ...

Selecting the appropriate color code based on a specified value

If the value of zoneTempDiff1 falls below 1.5, consider using temp: 1 color. If it exceeds 1.5, opt for temp: 2 color. The same logic applies to all different values such as -1, -2, 0, 1, 2, 3, 4, or 5, each corresponding to a specific color code. In cas ...

Using the "$parent" variable within multi-level directives

Currently, I am delving into a functional code. This particular code is designed to generate a basic JSON data structure by incorporating name:value pairs individually through a graphical user interface (GUI). Through a custom directive and its link functi ...

What could be the reason for the GET request not functioning properly in Node.js?

const express = require('express'); const mongoose = require ("mongoose"); const app = express(); const Student = require('../models/students'); require('dotenv').config(); const PORT = process.env.PORT || 3000; const co ...

ReactJS encounters errors even when the backend is returning a 200 OK status code

My ReactJS frontend receives an error when sending a GET request, even though the django backend terminal shows [10/Mar/2018 23:31:08] "GET /post/ HTTP/1.1" 200 930. I am using redux sagas in my project. In src/index.js: (index.js code snippet here) In ...