Deep copying of objects in angular?

I wonder if there is to avoid copying references to objects when you need to create a simple object with an array of built-in objects. The situation is this: I have a server that accepts JSON and applies some logic, and then stores the object in the database. let's say my form is for saving commands to the database. The server accepts the command as json. the team has an array of TeamMember objects, my form has a simple field for entering information about the member of the team member and adding it to the teamMembers array of the team. Now here is the problem when I add a team member to the list of arrays and want to add another team member when I enter the added element added in the field too! I know the reason

$scope.addTeamMember=function(teamMember){ $scope.team.teamMembers.push(teamMember); } 

and this is because I put the same link in the teamMembers array, so I add the same object several times. to avoid this, I have to create a new team member object, copy all the properties of teamMember and add it to the array.

  $scope.addTeamMember=function(teamMember){ var newTeamMember; /*<--- copy teamMember */ $scope.team.teamMembers.push(newTeamMember); /*and add newTeamMember*/ } 
+49
javascript angularjs
Jan 16 '13 at 14:15
source share
3 answers

Your question says you want to “avoid a deep copy,” but I'm not sure if that is for sure. It sounds like you just want to use angular.copy because you need to create a copy of the team member and add it to the array:

 $scope.addTeamMember = function(teamMember) { var newTeamMember = angular.copy(teamMember); $scope.team.teamMembers.push(newTeamMember); }; 
+115
Jan 16 '13 at 14:21
source share

This is the best documentation available.

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

there is a live example on the page that itself illustrates.

+6
Jul 08 '15 at 7:31
source share

I personally use this:

  function copyObjToObj(source, destination) { if(!angular.equals(source,destination)){ if (!!destination) angular.copy(source, destination); else destination = angular.copy(source); } return destination; } var destination = copyObjToObj(sourceObj, destination); 
0
Mar 19 '16 at 6:55
source share



All Articles