Struggling with the allocation of scope to a variable for manipulation

Struggling with assigning a scope object to a JavaScript variable in order to make some minor adjustments before sending it to my API. Surprisingly, any modifications made to the JavaScript variable end up changing the original scope object.

var recruitingCallListOutput = $scope.RecrutingCallingList.Recruit;

// making changes to recruitingCallListOutput

Unfortunately, these alterations are still affecting the scope object, which is definitely not what I intended. It seems like there's something about AngularJS that I'm not quite getting. Is there a way to extract the data and detach it from the scope?

Answer №1

When looking at your scenario, recruitingCallListOutput serves as a pointer to $scope.RecrutingCallingList.Recruit (check out https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0 for more information.) It's important to create a duplicate of $scope.RecrutingCallingList.Recruit.

If Recruit is a flat object, meaning no nested objects (only primitive values for properties), you can use the following:

var recruitingCallListOutput = Object.assign({}, $scope.RecrutingCallingList.Recruit);

If there are nested objects/arrays as property values, a deep copy is needed. Although it has been some time since I worked with Angular, you can try using

var recruitingCallListOutput = angular.copy($scope.RecrutingCallingList.Recruit)

You actually have the option to utilize angular.copy in both scenarios.

Answer №2

This code snippet does not pertain to AngularJS, but rather Javascript. This behavior is expected.

For instance, if you were to open the browser console (F12->Console) right now and execute the following:

var foo = {x:1};
var copy=foo;
copy.x=2;
console.log(foo.x);

You would observe {x:2} being displayed.

This behavior aligns with how object references work in languages like Javascript, C#, Java, etc. Changes made to a reference affect the original object due to the nature of referencing instead of copying.

To address this issue in your scenario, one approach is to extract the necessary values from the item and create a separate object for modifications.

For instance:

var recruitingCallListOutput = {
    name: $scope.RecrutingCallingList.Recruit.name,
    age:$scope.RecrutingCallingList.Recruit.age,
    modifiedSomething: $scope.RecrutingCallingList.Recruit.something + 42 //or any other required modifications
   ...and so forth.
};

Several methods exist to "clone" objects in Javascript, although caution is advised unless dealing with highly complex objects. Consider whether all properties of the original object are truly necessary, as only specific ones may need to be transmitted to the backend.

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 files being requested by jQuery Slimbox are not being retrieved properly

I am currently utilizing jQuery slimbox along with its Application Programming Interface (API). Below is the JavaScript code snippet that retrieves image paths through JSON and then triggers the slimbox using its API. $('#main-container').appen ...

Node.js does not provide the requested JSON code through Javascript get

I'm currently developing a discord bot that involves some JavaScript coding. Despite there being other options available, I have chosen to utilize JavaScript for specific reasons. The challenge I am facing is related to making a get request for JSON i ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

Error encountered in ThreeJS version r75: THREE.Animation is not defined as a constructor

Currently, I am utilizing the most up-to-date version of ThreeJS available. My goal is to import a Blender Model with rigged animations in ThreeJS. Despite conducting extensive research online and reviewing various tutorials, all references point to either ...

"Here's a neat trick for assigning the value of a div to a text box without any identifiers like id or

I needed a way to transfer the value of a .item div into an empty textbox without any specific identifier. Then, when the input loses focus, the value should be sent back to the original .item div. $(document).on("click", ".item", function() { $(this) ...

Utilizing the Ajax success callback to trigger a subsequent Ajax request as the loop iterates

I am currently working on a piece of javascript/jquery code that involves making ajax requests. The code snippet I have includes various variables and functions for handling external data sources and templates. var trigger = $('#loadTabl ...

An issue occurred while evaluating the Pre-request Script: Unable to access the 'get' property of an undefined object

I need help accessing the response of my POST request in Postman using a Pre-request Script. Script below : var mobiles = postman.environment.get("mobiles"); if (!mobiles) { mobiles =["8824444866","8058506668"]; } var currentMobile = mobiles. ...

Grouping results by month according to the datetime object in C#

I am working on an ASP.NET MVC application that includes a line chart displaying record counts and months on the X-axis and Y-axis respectively. To achieve this, I need to make an ajax call to the controller where the model holds information such as the r ...

Is there a way to produce a unique color using Stylus CSS?

Currently, I'm utilizing Express for Node.js and Stylus as the CSS engine. While Stylus is great, I'm facing some challenges in passing color variables or generating random colors. Despite attempting to use the javascript API for stylus, I find m ...

I'm looking to convert a Selenium webdriver test script from node.js to phantomjs - ghostdriver. Any tips on how to do this?

Recently, I started using Selenium and utilized node to run my scripts visually for easier testing. Now, I face the challenge of converting these tests into headless mode. Most resources I found only cover phantomjs and ghostdriver in conjunction with Java ...

What steps can I take to detect errors when generating a MongoDB ObjectId in Node.js?

var selectedCriteria = Mongoose.Types.ObjectId(payloadData.skillId), If an incorrect Id is passed, the following error message will be displayed: Error: Uncaught error: Argument passed in must be a single string of 12 bytes or a string of 24 hex charac ...

Is there a way to update a todo list on the same input field where I initially added it in a React application?

I am new to using React js and currently working on a project that I found on YouTube. The issue I am facing is related to editing tasks - I would like to be able to edit them within the same input field where I add tasks. Unfortunately, I am not sure how ...

What is the best approach to creating a custom directive in AngularJS that can be used to display a set of items in an

I am a novice in the world of AngularJS and I have set out to create a custom directive that will display specific items from an ng-repeat loop. Here is my current custom directive: (function(module) { module.directive('portfolioList', function ...

having trouble customizing react-select to fit bootstrap sm styling

I am currently utilizing react-select multi-select feature from the npm package at this link. My project is styled using bootstrap 4, and I am aiming to have the react-select component match the size of the sm class in Bootstrap. To achieve this, I attempt ...

How can you prevent JQuery AJAX from automatically redirecting after a successful form submission?

Encountered an issue with loading http://example.com/signup.ashx: The redirect from 'http://example.com/signup.ashx' to '' was blocked by the CORS policy. This is due to the absence of 'Access-Control-Allow-Origin' header on t ...

Ensuring the synchronization of dynamic select list parameters within AngularJS

I am facing an issue with a form that has a dynamically generated select list. The values for this list are retrieved from the scope, and the currently selected value is also retrieved from the scope. However, there seems to be a synchronization problem. ...

Develop a custom cell editor for ag-Grid and insert it into a designated location within

I am currently working with Angular 16 and AgGrid 30. My goal is to have the cell editor created in a different location than its default position, which is within a div element at the bottom of the body with these classes: ag-theme-material ag-popup. I w ...

Sequelizejs establishes a belongsToMany relation with a specified otherKey

I am currently developing an app centered around songs and artists, and here is the database schema I have designed: Each Song can have multiple Artists associated with it, and each Artist can be linked to several Songs as well. This establishes a many-to ...

Get answers for AngularJS ng-repeat by initializing inputs with the corresponding answer object

I have a set of questions coming from an AJAX response that I am displaying using ng-repeat. Each question input in the list needs to be connected to a separate answers array through its ng-model. Here is an example of how the question array looks: booki ...

The concealment of the container is ineffective when attempting to hide it until all cached images are

My website has a background and a main container. I wanted to hide the container until the entire page had loaded, so I included #cover{opacity:0} at the beginning of the page and $(window).load(function() { $('#cover').css('opacity&apo ...