Revisiting Angular: The Curious Case of an Object Attribute Altering Attributes on Two Separate Objects

Creating a website with Angularjs involves working with an array of objects:

$scope.fieldsToShow = [
    {
        "fields": {},
        "type": "LOGGED_IN"
    },
    {
        "fields": {},
        "type": "PERSONAL",
        "user": 2,
        "name": "Rick Astley"
    }
];

A specific object is selected and stored in a variable:

var $scope.currentObject = $scope.fieldsToShow[1];

Users can modify the object using checkboxes:

<input ng-model="currentObject.fields.a" type="checkbox">

This updates both $scope.currentObject:

{
    "fields": {
        "a": true
    },
    "type": "PERSONAL",
    "user": 2,
    "name": "Rick Astley"
}

and the original object in $scope.fieldsToShow:

$scope.fieldsToShow = [
    {
        "fields": {},
        "type": "LOGGED_IN"
    },
    {
        "fields": {
            "a": true
        },
        "type": "PERSONAL",
        "user": 2,
        "name": "Rick Astley"
    }
];

After switching back to the first object, clicking the checkbox again correctly updates the fields object. So far so good.

Next step is adding an inner object within the fields object. A new checkbox is created:

<input ng-model="currentObject.fields.anInnerObject.val" type="checkbox">

Switching back to the PERSONAL object and clicking the checkbox correctly updates both the $scope.currentObject:

{
    "fields": {
        "anInnerObject": {
            "val": true
        }
    },
    "type": "PERSONAL",
    "user": 2,
    "name": "Rick Astley"
}

and the original object in $scope.fieldsToShow:

$scope.fieldsToShow = [
    {
        "fields": {},
        "type": "LOGGED_IN"
    },
    {
        "fields": {
            "anInnerObject": {
                "val": true
            }
        },
        "type": "PERSONAL",
        "user": 2,
        "name": "Rick Astley"
    }
];

Upon switching back to the LOGGED_IN object, clicking the checkbox unexpectedly changes the value of "anInnerObject" in the PERSONAL object to true.

The baffling behavior has left me wondering how this could happen despite several efforts to debug and seek advice. Any insights or suggestions are greatly appreciated!

Answer №1

It is important to realize that $scope.currentObject and the original object in $scope.fieldsToShow are referencing the same object. They are not separate entities but merely point to the same memory location. This is how non-primitive type references function in Javascript.

If you wish to have distinct objects, you must clone it before using:

var $scope.currentObject = angular.copy($scope.fieldsToShow[1]);

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 library called "Error: JSON input ended unexpectedly"

I am currently operating a server using node.js and Express v4.0 Additionally, I am utilizing the request library. However, when receiving a response from the server, I encounter an Uncaught SyntaxError: Unexpected end of JSON input. The response I receiv ...

Transitioning from bootstrap 3 to 5 results in an increase in all sizes across the board

After transitioning from bootstrap 3 to 5, I noticed that all the elements on every page of my app became enlarged. The only component using bootstrap in this image is the dropdown menu with three vertical dots. https://i.sstatic.net/Ma27h.png https://i.s ...

What is the procedure for automatically playing the next audio track in HTML5 after the current one finishes playing

When trying to play a single MP3 file, the code below is designed to skip to a specific part of the track and then start playing from that position. However, despite the cursor moving to the correct spot in the MP3, it fails to play upon clicking the Sta ...

Introduce a fresh parameter into the promise all chain

I am using the code below and it is functioning as expected. However, I now need to incorporate the modifyOpt() function. Currently, the code works and returns args[2] but I also need to include another step... I want to pass the return value (port) from ...

What is causing my Bootstrap Controls to malfunction?

I'm trying to create a Bootstrap carousel that shows 3 items at once and includes controls to switch between them. The carousel I've made does display the three items, but for some reason, the controls are not responding when clicked. I'm un ...

Refreshing the current window with the ``Window.location.reload()`` function

I have integrated a map that displays clients using markers. The map I am utilizing is Leaflet with an AngularJS directive. The issue I am facing is that when I initially access the map, it functions correctly. However, when I change routes, all the marke ...

Selling beyond webpack's confines

Today I had an interesting thought and couldn't find much information on it, so I decided to share some strange cases and how I personally resolved them (if you have a better solution, please feel free to comment, but in the meantime, this might be he ...

Definition of Stencil Component Method

I'm encountering an issue while developing a stencil.js web component. The error I'm facing is: (index):28 Uncaught TypeError: comp.hideDataPanel is not a function at HTMLDocument. ((index):28) My goal is to integrate my stencil component i ...

Utilizing nprogress.Js for a Dynamic Progress Bar

I'm trying to create a progress bar similar to the one on YouTube using the nprogress.js plugin. However, I want the progress to start from the middle of the page, like this: start | --------------------------------------------> | end Instead of: ...

Utilize a viewpoint alteration alongside a floating effect on a specific element

I thought this would be an easy task, but I seem to be missing something as it doesn't work for me. The goal is to use the perspective() and rotateY() functions in a transform to create a perspective effect on an element. Additionally, there should b ...

Where should I place my custom menu script in Wordpress and how do I do it?

I am currently exploring the realms of PHP, Wordpress, and Javascript as I endeavor to transform my website, crafted with CSS and HTML, into a dynamic theme for Wordpress using PHP. One particular feature on my site is an off-screen menu that smoothly ope ...

Discovering the offset location using touchmove

Struggling with a code for dragging/moving an element via touchscreen. The code is functional, but encounters a common issue - unable to drag from the touchpoint itself. Every movement initiates from the edge of the element, no matter where the touch begin ...

Experiencing an unexpected abundance of console logs when implementing React Hooks

I am attempting to retrieve data from an API. The desired result is being obtained, but when I attempt to log it to the console, it logs 4 times. Within my app.js, I am utilizing the fetchData function: import React, {useEffect, useState} from 'rea ...

Executing jQuery AJAX with PHP using 'POST' method to receive and process PHP code

Something seems to have gone wrong with my setup; it was functioning properly before but is now encountering issues. When trying to make a POST call from an HTML file to a php file (which fetches data from a REST API), instead of receiving the expected API ...

Hovering into Transition Time

My article card has a transition on the top attribute of the info div, which is supposed to be smooth and last for 0.3 seconds. However, the description suddenly appears during this transition. I'm trying to figure out why this is happening and how to ...

What is the reason in AngularJS for requiring directive attributes to be hyphen-separated while their scope variables are camelCased?

Here is an example in Html: <!-- Note 'display-when' is hyphenated --> <wait-cursor display-when="true"></wait-cursor> Then, when defining it in the directive: scope: { // Note 'displayWhen' is camelCased show: ...

Is there a way to stop the execution of myFunc after it has been performed 5 times using clearInterval?

This code is designed to notify online shoppers that they need to choose a color from a dropdown menu before adding an item to their shopping cart. If no color is selected, the text will blink to alert them. How can I modify this code so that the blinking ...

Strange Phenomenon in Node/Express.js: Vanishing Array Elements

My goal is to extract information from a database and store it in an array for further processing. However, I am facing an issue where the elements disappear after being added in a for-loop, resulting in an empty array. // PROBLEM: all_prices-elements dis ...

Utilizing React JS to dynamically incorporate form values into objects

I have an array of objects where I need to add a key value State : const [row, setRow] = useState([{ nameofthework: "", schedulerefNo: "", unitprice: "", qty: "", uom: "", gst: "", total: "& ...

Building a custom onChange event handler in Formik allows for greater

I want to modify the onChange function in formik input so that it converts the value from a string to a number. However, I'm unable to change the behavior as expected and the console.log doesn't show up on the screen. It seems like Formik's ...