0

I have an angular controller connected to a node/express server. Response data for a request is called in an $http.get where I can set response=$scope.x. x can then be interacted with and changed. I could then set $scope.y = $scope.x, and any changes to y would result in x changing as well. However, I basically want to clone the response so as to have the original response data set to different variables without them changing each other.

Consider a response where response.name = "Joe".

$scope.x = response;
$scope.y = response;

In my code or view/model I could change x.name as such:

$scope.x.name = "Bob"

However, I would like $scope.y.name to still equal "Joe".

I could use two separate get requests to retrieve the same response, but I'd like to pass the response into a function which will dynamically change that data and make a new version of it based on a for loop. Is there a clean, "angular" to do this? Or a simple javascript function?

mjoyce91
  • 316
  • 2
  • 19

2 Answers2

1

angular has a built in utility for this angular.copy()

$scope.x = response;
$scope.y = angular.copy(response);

Can also be used to clean out unwanted properties that angular can create such as hashkeys used in ng-repeat tracking

angular.copy() docs

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

The short answer is

$scope.y = angular.copy($scope.x)

or

$scope.y =_.clone($scope.x)

if you are using lodash/underscore.


The long answer, unfortunately is longer, and necessitates you learning about the difference between byReference and byValue variable types. To understand it please see this answer.

Community
  • 1
  • 1
Gabriel C. Troia
  • 3,180
  • 2
  • 16
  • 17