Why and when to use angular.copy? (Deep Copy)

前端 未结 7 676
無奈伤痛
無奈伤痛 2020-12-04 07:39

I\'ve been saving all the data received from services direct to local variable, controller, or scope. What I suppose would be considered a shallow copy, is that correct?

相关标签:
7条回答
  • 2020-12-04 08:16

    When using angular.copy, instead of updating the reference, a new object is created and assigned to the destination(if a destination is provided). But there's more. There's this cool thing that happens after a deep copy.

    Say you have a factory service which has methods which updates factory variables.

    angular.module('test').factory('TestService', [function () {
        var o = {
            shallow: [0,1], // initial value(for demonstration)
            deep: [0,2] // initial value(for demonstration)
        }; 
        o.shallowCopy = function () {
            o.shallow = [1,2,3]
        }
        o.deepCopy = function () {
            angular.copy([4,5,6], o.deep);
        }
        return o;
    }]);
    

    and a controller which uses this service,

    angular.module('test').controller('Ctrl', ['TestService', function (TestService) {
         var shallow = TestService.shallow;
         var deep = TestService.deep;
    
         console.log('****Printing initial values');
         console.log(shallow);
         console.log(deep);
    
         TestService.shallowCopy();
         TestService.deepCopy();
    
         console.log('****Printing values after service method execution');
         console.log(shallow);
         console.log(deep);
    
         console.log('****Printing service variables directly');
         console.log(TestService.shallow);
         console.log(TestService.deep);
    }]);
    

    When the above program is run the output will be as follows,

    ****Printing initial values
    [0,1]
    [0,2]
    
    ****Printing values after service method execution
    [0,1]
    [4,5,6]
    
    ****Printing service variables directly
    [1,2,3]
    [4,5,6]
    

    Thus the cool thing about using angular copy is that, the references of the destination are reflected with the change of values, without having to re-assign the values manually, again.

    0 讨论(0)
提交回复
热议问题