使用angular.copy

时间:2019-06-26 10:25:38

标签: angularjs

我正在使用angular.copy,但是它在循环对象和分配变量上也很好用。

angular.copy与循环需要获取赋值的变量相比有什么用?

2 个答案:

答案 0 :(得分:0)

angular.copy()创建一个新对象作为深层副本,这意味着这两个对象将彼此独立。

进行常规循环和分配,我假设您正在使用=运算符,这意味着更改原始对象的属性将更改复制对象的相应属性,反之亦然。

例如,考虑一个对象:

let obj1 = {something};

let obj2; //you want to copy obj1 into obj2

//case 1: using angular.copy
obj2 = angular.copy(obj1);  

//case 2: using =
obj2 = obj1;

在情况1中:如果您更改obj1obj2或两者都更改,则不会影响彼此。

但是在情况2中:如果更改obj1obj2,则该更改会反映在另一个对象中。

因此, 使用angular.copy(),这两个对象将保持分离,并且更改不会相互反映。

答案 1 :(得分:0)

在将对象或数组的值分配给另一个变量时,请使用 angular.copy,并且该对象的值不应更改。

没有深层复制或使用 angular.copy ,更改属性的值或添加任何新属性,更新所有对象,引用同一对象。

角度:js文件

var app = angular.module('copyExample', []);
app.controller('ExampleController', ['$scope',
  function($scope) {
    $scope.printToConsole = function() {
      $scope.main = {
        first: 'first',
        second: 'second'
      };

      $scope.child = angular.copy($scope.main);
      console.log('Main object :');
      console.log($scope.main);
      console.log('Child object with angular.copy :');
      console.log($scope.child);

      $scope.child.first = 'last';
      console.log('New Child object :')
      console.log($scope.child);
      console.log('Main object after child change and using angular.copy :');
      console.log($scope.main);
      console.log('Assing main object without copy and updating child');

      $scope.child = $scope.main;
      $scope.child.first = 'last';
      console.log('Main object after update:');
      console.log($scope.main);
      console.log('Child object after update:');
      console.log($scope.child);
    }
  }
]);

// Basic object assigning example

var main = {
  first: 'first',
  second: 'second'
};
var one = main; // same as main
var two = main; // same as main

console.log('main :' + JSON.stringify(main)); // All object are same
console.log('one :' + JSON.stringify(one)); // All object are same
console.log('two :' + JSON.stringify(two)); // All object are same

two = {
  three: 'three'
}; // two changed but one and main remains same
console.log('main :' + JSON.stringify(main)); // one and main are same
console.log('one :' + JSON.stringify(one)); // one and main are same
console.log('two :' + JSON.stringify(two)); // two is changed

two = main; // same as main

two.first = 'last'; // change value of object's property so changed value of all object property 

console.log('main :' + JSON.stringify(main)); // All object are same with new value
console.log('one :' + JSON.stringify(one)); // All object are same with new value
console.log('two :' + JSON.stringify(two)); // All object are same with new value

HTML对应的代码:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="copyExample" ng-controller="ExampleController">
  <button ng-click='printToConsole()'>Explain</button>
</div>