Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copying objects in angular?

I wonder if there is away to avoid copying references to objects when you need to create a simple object which has an array of embedded objects.The situation is as follow: I have server which accepts a JSON and applies some logic then stores the object in DB. lets say my form is for saving teams in DB. The server accepts team as json. the team has an array of TeamMember objects, my form has a simple field to enter team member info and add it to team teamMembers array. Now here is the problem, when I add a team member to array list and want to add another team member when I type into the field the added member is changed also !. I know the reason

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

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

 $scope.addTeamMember=function(teamMember){        var newTeamMember; /*<--- copy teamMember */        $scope.team.teamMembers.push(newTeamMember); /*and add newTeamMember*/     } 
like image 914
Adelin Avatar asked Jan 16 '13 14:01

Adelin


People also ask

Is Angular copy a deep copy?

Example# The angular. copy function takes an object, array or a value and creates a deep copy of it.

What is shallow copy and deep copy in Angular?

shallow copying. A deep copy means that all of the values of the new variable are copied and disconnected from the original variable. A shallow copy means that certain (sub-)values are still connected to the original variable.

How do you copy a deep object?

Copy an Object With Object.assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.


1 Answers

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

$scope.addTeamMember = function(teamMember) {    var newTeamMember = angular.copy(teamMember);    $scope.team.teamMembers.push(newTeamMember); }; 
like image 194
Ben Lesh Avatar answered Oct 14 '22 19:10

Ben Lesh