Manipulating AngularJS variables that are outside of its designated scope should be restricted

Something strange is happening in my code. I created a function called "insertTstData" outside of any angular scope, and when it is called from another function named "save" within a controller named "remark", it somehow manipulates a local variable and the change reflects across all variables with the same content, even those not directly related.

This situation is so absurd that I find it difficult to explain without giving you the full context.

Here's how it all starts: I use the $http service to retrieve a JSON configuration file and store it in a scope variable while inside the "main" controller (the parent of the problematic "remark" controller):

 $http.get(path + 'remarkConfig.json')
        .then(function (response) {
            //modify fields
            $scope.remark = response.data; //this variable will be used later on
            $scope.dummy = response.data; //this variable gets changed unexpectedly
});

Although these variables are arrays of objects, let's simplify them as objects with two properties for now:

{"p1":"PROP ONE", "p2": "PROP TWO"}

There's a button within the "remark" controller that triggers the save function passing $scope.remark to it:

<md-button class="amaButton md-raised" ng-click="save(data, remark)" aria-label="save">{{translate.save}}</md-button>

Below is the save function within the "remark" controller's scope which also has access to the "main" scope:

$scope.save = function (data, remarks) {
    console.log($scope.dummy);
    console.log($scope.remark);
    console.log(remarks);
    var originalRemarks = {};    
    originalRemarks.codes = remarks;
    //insert TSTs into data, formatting <>-like remarks
    var response = insertTstData(data, $scope.tst, remarks);   
    console.log($scope.dummy);
    console.log($scope.remark);
    console.log(remarks);
    console.log(originalRemarks.codes);
}

Now, let's take a look at the troublesome function insertTstData (outside any controller/scope):

function insertTstData(data, tst, remarks) {
    var rem = remarks; 
    rem.p1="";
    var response={"data": data, "remarks": rem};
    return response;
}
//after this function executes, every variable's p1 is set to an empty string!

I have thoroughly checked the code and cannot find any other changes being made to these variables elsewhere. Could they all be pointing to the same value due to some unknown mechanic?

Answer №1

Understanding the distinction between a shallow copy and a deep copy of a variable is crucial. In JavaScript, a basic assignment of an object (not a primitive type) is done by reference, resulting in a shallow copy.

var remarks = {"p1":"PROP ONE", "p2": "PROP TWO"}
var rem = remarks; //the assignment

With this setup, any modifications to the object in remarks will also affect rem, and vice versa. To create two separate objects (a deep copy), angular.copy should be utilized.

var rem = angular.copy(remarks)

This approach ensures that both variables point to distinct memory locations, representing two unique objects.

https://i.sstatic.net/4GSp3.jpg

Answer №2

Whenever you assign a variable rem (var rem = remark) in JavaScript, it creates a reference to the original object rather than making a copy of it. This means that any modifications made to rem will also affect the parent object.

I recommend using the clone() method to create a duplicate object instead.

For more information on how to correctly clone a JavaScript object, please visit this link

Answer №3

Another option is to utilize angular.copy(remarks) for generating a thorough duplicate of the item, whether it's an object or an array.

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

Minimal Space Separating Footer Division and Body Element

While there are numerous discussions online about fixing footer alignment issues, I've encountered a unique problem that needs addressing. The issue at hand is a 29px gap between the bottom of the footer and the <body> tag on my webpage, which ...

Center JQuery within the current screen

My implementation of Jquery dialog is as follows: <body> <div id="comments_dialog"> Insert a comment <form> <input type="text" id="search" name="q"> </form> </div> .... </body> dialog = $( "#com ...

Coordinating a series of maneuvers

When it comes to coordinating multiple sequential actions in Redux, I find it a bit confusing. I have an application with a summary panel on the left and a CRUD panel on the right. My goal is to have the app automatically update the summary after a CRUD op ...

What is the best way to populate dropdown menus using JavaScript?

I'm facing an issue with my ajax request where I am unable to populate the options of a select tag. This problem is occurring in multiple blocks where the select tag serves the purpose of choosing a type of product. Here is how my select tag looks li ...

Using AngularJS location.path for unique custom URLs

Control Code: $scope.$on('$locationChangeStart', function () { var path = $location.path(); var adminPath = '/admin/' ; if(path.match(adminPath)) { $scope.adminContainer= function() { return true; }; }); HTML <div clas ...

What is the process of sending an HTTP/HTTPS request from a Node.js server?

Currently diving into the world of Node.js, I am experimenting with using a Node.js Application on cPanel to generate a JSON response upon accessing its URL. Upon visiting the app's URL, it seems that the Node.js server is functioning correctly. Afte ...

Images not displaying in Ng-bootstrap Carousel

After using an outdated version of Bootstrap (0.13.4 & 0.14.1), I am now in the process of upgrading to a newer version. The old slider feature was functioning properly; however, it no longer displays images when switching to the new version. This behavio ...

AngularYelp: Node Integration for Enhanced Functionality

Embarking on a new learning journey here, so please bear with me... Discovered node-yelp while browsing Yelp's API docs. Check it out here. // Request API access: http://www.yelp.com/developers/getting_started/api_access var Yelp = require('yel ...

Is there a proper method for populating an HTML text with values from a form?

As a newcomer, I could really use some guidance here :) I'm trying to populate text with various words, numbers, and calculation results from a form. This is my initial attempt for just one field/word, and it appears to be functioning correctly. Do y ...

Exploring the loading of stateful data in ReactJS and implementing optimizations

Exploring the world of ReactJS in conjunction with Django Rest Framework (DRF) def MyModel(model): ... status = ChoiceField(['new', 'in progress', 'completed'...]) In my application, I have dedicated sections for eac ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

Ways to present a Nuxt page as a reply from an express route

How can I achieve a similar functionality to res.render on a Nuxt page? The project is using the nuxt-express template, which combines Nuxt and Expressjs. Although Nuxt provides nuxt.render(req, res) and nuxt.renderRoute, I am having trouble making it wo ...

The custom filter in AngularJS fails to activate when a click event occurs

I am trying to customize the filtering of my table data based on selected conditions from a dropdown menu. I have created an AngularJS custom filter and passed all the necessary parameters. The desired functionality is that if no conditions are selected, ...

The AJAX request is not triggered before the postback when using a LinkButton in ASP

I am facing an issue with running an insert statement using a button in my application. Although it is functional, I have noticed that whenever I click the button, the Page_Load function runs before the ajax statement executes. How can I ensure that the a ...

Rapidly verifying PHP arrays with jQuery/AJAX

I am looking for a way to validate values within a PHP array in real-time without the need to click a submit button by utilizing jQuery/AJAX. As users type an abbreviation into a text field, I want to instantly display whether the brand exists (either v ...

What is the correct way to utilize JavaScript's clearTimeout function with arguments?

I came up with a simple function to mimic the movement of window blinds. It runs on a server that receives requests with a direction parameter determining whether the blind should move UP, DOWN, or STOP. The simulation works like this: upon receiving a re ...

Converting a "String" value to a specific "Type" in Angular 2 using TypeScript

This is my current object, Home points to the import statement for Home component. import { Home } from '../home/home'; arr = [ { name: "Home", root: Home, icon: "calc" } ]; This is what I want to achieve: import { Home } from & ...

Tips for incorporating several d3 elements on a single webpage

I am currently facing an issue where I am attempting to add a line graph below a d3 map, but the map and line graph are appearing below where the map should be located. I have tried creating separate div tags with distinct id's, but I am unsure of wha ...

The value retrieved from redux appears to be varying within the component body compared to its representation in the return

Trying to fetch the most recent history value from the redux store to pass as a payload is presenting a challenge. When submitting a query, the history updates and displays the latest value within the map() function in return(), but when checking at // CON ...

Will it function properly if it is (NULL)?

Here's the code snippet I'm currently using: <html> <head> <link type="text/css" rel="stylesheet" href="html.css" /> <script type="text/javascript"> function getName() { if(name) alert("Did y ...