Reputation: 18557
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?
Upvotes: 0
Views: 1111
Reputation: 7899
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 .
Upvotes: 1
Reputation: 10148
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()
Upvotes: 0
Reputation: 171669
Use angular.copy()
$scope.form= response.data.shooter;
oldData= angular.copy(response.data.shooter);
Upvotes: 1