简体   繁体   中英

Having trouble with assigning scope to variable to manipulate

Attempting to assign a scope object to a JavaScript variable to do minor manipulation before sending to my API. However, any changes made to the JavaScript variable change the scope object.

var recruitingCallListOutput = $scope.RecrutingCallingList.Recruit;

// manipulation of recruitingCallListOutput

The manipulation actually still updates the scope object which is not desired. Feel I am not understanding something in AngularJS correctly. Is there a way to grab the data and detach it from the scope?

In your example, recruitingCallListOutput is a reference to $scope.RecrutingCallingList.Recruit (see https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0 for more detail.) You will want to make a copy of $scope.RecrutingCallingList.Recruit.

If Recruit is a shallow object, meaning no nested objects (property values are primitives only), you can simply do

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

If you have nested objects/arrays as property values, you'll need to deep copy. It's been a while since I have been in the angular world, but

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

you could actually use angular.copy in both examples.

This is nothing to do with AngularJS. It's Javascript, and it's expected behaviour.

For example, if you open the browser console (F12->Console) right now and run this:

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

you will see {x:2} printed out.

This is the same behaviour you would expected for any object reference in Javascript, C#, Java, etc. Because you are making a reference and not a copy, any changes to the reference are actually changes to the original.

The simplest way to solve this problem in your case is to copy the values you are interested in from the item in question into a totally separate object and modify that copy.

eg

var recruitingCallListOutput = {
    name: $scope.RecrutingCallingList.Recruit.name,
    age:$scope.RecrutingCallingList.Recruit.age,
    modifiedSomething: $scope.RecrutingCallingList.Recruit.something + 42 //or whatever modifications you need to make
   ...and so on.
};

There are ways to "clone" an object in Javascript but unless your object is really really complex I would be careful. And consider if you really need all of the properties of the original object anyway, perhaps you only need to send some of them to your backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM