0

I have data as follow:

$scope.form= response.data.shooter;
oldData= response.data.shooter;

I have an issue in here:

Both have the same object array.

When I delete any value from oldData, it is also getting removed from $scope.form.

The code is as follows:

$.each(oldData, function(i, e) {
  console.log(oldData[e], $scope.form[e]);
  oldData[e] = '';
  console.log(oldData[e], $scope.form[e]);
});

I have searched regarding this, but no luck.

Can anyone tell me, how to create a replica of scope to handle it separately regardless of sync between two array objects i.e. independent replica of scope so that if I make changes in that replica should not affect in scope?

3 Answers 3

1

Use angular.copy()

$scope.form= response.data.shooter;
oldData= angular.copy(response.data.shooter);
Sign up to request clarification or add additional context in comments.

Comments

1

Yes you can use angular.copy .For copy the object to other.

angular.copy(source, [destination]);

oldData = angular.copy($scope.form);

angular.copy($scope.leader, oldData);

both you can use

https://docs.angularjs.org/api/ng/function/angular.copy

also you can have a look at lodash and underscore

This library provide very nice to method .

Comments

0

Well @Charlietfl is correct I would just like to add some explanation to the issue and solution

Using = , you're actually assigning reference of response.data.shooter to both $scope.form and oldData and as reference is the same updating one would affect the other (same concept as shallowCopy in C++). To avoid these kind of issues you need to make deep copies of the objects and the way to do that in angular is angular.copy()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.