深度复制的角度对象? [英] Deep copying objects in angular?

查看:99
本文介绍了深度复制的角度对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有去避免复制对象的引用,当你需要创建一个简单的对象具有嵌入式objects.The情况的阵列是如下:我有一个接受JSON和应用一些逻辑,然后存储服务器在DB的对象。可以说,我的方式是在数据库保存队。服务器接受团队JSON。球队有TeamMember对象的数组,我的状态有一个简单的字段中输入团队成员的信息,并把它添加到组队teamMembers阵列。现在,这里的问题是,当我一个团队成员添加到数组列表,并希望添加其他的团队成员,当我键入领域添加的成员也发生了变化!我知道原因

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

,这是因为我把相同的参考到teamMembers阵列,所以我有相同的对象增加好几倍。
避免这种情况我应该创建一个新的团队成员对象,复制所有teamMember属性和添加它的阵列。

  $ scope.addTeamMember =功能(teamMember){
       VAR newTeamMember; / *< ---副本teamMember * /
       $ scope.team.teamMembers.push(newTeamMember); / *和添加newTeamMember * /
    }


解决方案

您的问题说,要避免深度拷贝,但我不知道这是正确的。这听起来像你只是想使用 angular.copy 的,因为你需要创建团队成员的副本,添加到数组:

  $ scope.addTeamMember =功能(teamMember){
   VAR newTeamMember = angular.copy(teamMember);
   $ scope.team.teamMembers.push(newTeamMember);
};

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*/
    }

解决方案

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

这篇关于深度复制的角度对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆