Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - 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*/
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...