사물을 비스듬히 복사하고 있습니까?
내장된 오브젝트가 배열된 심플한 오브젝트를 작성해야 할 때 오브젝트에 대한 참조를 복사하지 않도록 할 수 있는 방법이 있는지 궁금합니다.상황은 다음과 같습니다.서버가 JSON을 받아들여 로직을 적용한 후 오브젝트를 DB에 저장합니다.제 폼은 팀을 DB에 저장하기 위한 것입니다.서버는 팀을 json으로 받아들입니다.팀에는 TeamMember 객체의 배열이 있으며, 내 양식에는 팀 구성원 정보를 입력하고 teamMembers 배열에 추가하는 간단한 필드가 있습니다.여기서 문제가 발생합니다.팀 멤버를 어레이 목록에 추가하고 필드에 입력할 때 다른 팀 멤버를 추가하려고 하면 추가된 멤버도 변경됩니다!나는 이유를 안다.
$scope.addTeamMember=function(teamMember){
$scope.team.teamMembers.push(teamMember);
}
그리고 teamMembers 배열에 동일한 참조를 넣었기 때문에 동일한 오브젝트를 여러 번 추가했기 때문입니다.이를 피하기 위해 새로운 팀원 객체를 만들고 모든 teamMember 속성을 복사하여 어레이를 추가해야 합니다.
$scope.addTeamMember=function(teamMember){
var newTeamMember; /*<--- copy teamMember */
$scope.team.teamMembers.push(newTeamMember); /*and add newTeamMember*/
}
당신의 질문은 "심층 복사를 피하고 싶다"고 말했지만, 그것이 정확한지 잘 모르겠습니다.angular.copy를 사용하는 것 같습니다.팀 멤버의 복사본을 생성하여 어레이에 추가해야 하기 때문입니다.
$scope.addTeamMember = function(teamMember) {
var newTeamMember = angular.copy(teamMember);
$scope.team.teamMembers.push(newTeamMember);
};
이것은 입수 가능한 최고의 문서입니다.
https://docs.angularjs.org/api/ng/function/angular.copy
이 페이지에는 자명하게 설명되는 생생한 예가 있습니다.
개인적으로 사용하는 것은 다음과 같습니다.
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);
언급URL : https://stackoverflow.com/questions/14360401/deep-copying-objects-in-angular
'itsource' 카테고리의 다른 글
Spring Boot 자동 구성에 주석 대신 spring.factories를 사용하는 이유는 무엇입니까? (0) | 2023.03.13 |
---|---|
MUI의 CSS 자 선택기 (0) | 2023.03.13 |
Amazon Cloudwatch Logs Insights with JSON 필드 (0) | 2023.03.13 |
Angularjs의 앵커 링크? (0) | 2023.03.13 |
'속성이 '없음' 유형에 없습니다.' (0) | 2023.03.13 |