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.

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

AngularJS - Custom directive to extract a property value from an object

Currently, I am using the following for loop to retrieve the parent category: angular.forEach(queryTicketCategories, function(category) { if(category.id === $scope.ticketCategory.parentId) { $scope.parent = category; } }); I am looking fo ...

The text-center alignment in Bootstrap doesn't seem to be applying to buttons

After spending a considerable amount of time trying to center two buttons in Bootstrap, I came across the "text-center" class offered by Bootstrap. However, no matter where I include this class, it doesn't seem to have any effect on the alignment of t ...

Angular 1.x just got a major upgrade with the introduction of the UI-Router v1.0+ $trans

I am on the hunt for a method that can replicate the functionality of UI-Router's $rootScope.$on('$stateChange...' from before version 1.0. Although I am aware of the new $transitions service, I am struggling to get it to work in the same wa ...

What is the purpose of using a hash in a WebSocket handshake?

When establishing a Websocket connection, the client initiates by connecting to a tcp socket on a server and then performs a handshake. In the client's handshake, there is a base64 encoded key (Sec-WebScoket-Key). The expected response from the serv ...

Issues with data retrieval from PHP file in AJAX submission

During my attempts to utilize AJAX for submitting data to a PHP file, I encountered an issue where the submission was successful and I could receive a message echoed back from the PHP file. However, when trying to echo back the submitted data or confirm if ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

jQuery: Track mouse movement with a delay

I'm looking to create a div that follows cursor movement with a slight delay, similar to the effect seen on this website: In the example link provided, you can observe that the 'follower' has a brief delay in its animation. I attempted to ...

Configuring $scope.items for Angular Data Binding

I have a service that includes the following function, public object Get(AllUsers request) { var users = XYZ.GetAllUsers(); var userList = users.Cast<XYZ>(); return new AllUsers { UsersAcc = userList.Select(ConvertToEntity). ...

Determine which children should be displayed in a Kendo treeview based on the field titled "ParentId"

After converting a list of records into JSON format, I am looking to transform this data into a hierarchical KendoTreeView. Here is the JSON data: [ { "id": 1, "name": "A", "parentID": 0, "hasItems": "true" }, { "id": 2, "name": "B", "parentID": 1, "has ...

Tips for triggering jquery code when a variable containing a CSS attribute is modified

I have a specific requirement where I need to reset the scrollleft value to 0 on my wrapper whenever a particular CSS property changes. Although I am new to using jQuery and haven't worked with variables much, I believe I need to create a variable to ...

Preventing responsive elements from loading with HTML scripts

Currently, I am utilizing the Gumby framework which can be found here. Everything appears to be running smoothly. My goal is to incorporate a mobile navigation list where the links are grouped under a single button, as outlined here. Initially, this funct ...

The modal window pops up immediately upon the first click

Experience a dynamic modal element that springs to life with just the click of a button or an image. The magic lies in the combination of HTML, CSS, and jQuery code: <div id="modal-1" class="modal"> <div class="button modal-button" data-butto ...

The bootstrap navbar dropdown feature isn't functioning properly on iPhones

Currently utilizing "bootstrap": "~3.3.4" within the mean.js framework, I am facing an issue with the navbar dropdown menu. On desktop, everything functions as expected - the dropdown opens and remains open when the icon is clicked. However, once deployed ...

Create a new button dynamically within an HTML table row using pure JavaScript programming techniques

Currently, I am retrieving JSON data from an API and then displaying this data in an HTML table using plain JavaScript. My goal is to dynamically add a button at the end of each row for additional functionality, but so far, I have been unable to figure out ...

Tips on sending form data, including a file, to Ajax using the onclick() method

My Modal Includes a Form: <div class="modal fade bs-example-modal-lg" id="myMODALTWO" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="form-content"> <div class="modal-dialog modal-lg" role="document"> ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

Using React, a link to the same component is created, but a subcomponent is mistakenly using an outdated version of

Here, we have a SubComponent and a MainComponent created to showcase an image collection. The Subcomponent allows you to toggle between pictures in the collection using the onclick() event. The MainComponent also includes links to other collections, which ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

Tips for broadcasting the blob

I am currently working on a radio system project that involves streaming live audio from a microphone to the user in real-time. However, I am new to using node.js and unsure of how to achieve this. Can anyone provide guidance on how to stream the audio fro ...

Optimizing Window Width with React.js and CSS

I'm currently in the process of building a responsive website with react. I am utilizing CSS stylesheets for styling and have used @media queries to ensure responsiveness. However, I've encountered an issue while testing in Chrome where the elem ...