Deep copying objects in angular?

后端 未结 3 435
野性不改
野性不改 2020-12-05 01:39

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

相关标签:
3条回答
  • 2020-12-05 02:10

    This is the best documentation available

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

    there is a live example as well on the page which is self illustrative.

    0 讨论(0)
  • 2020-12-05 02:10

    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 讨论(0)
  • 2020-12-05 02:12

    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);
    };
    
    0 讨论(0)
提交回复
热议问题