为什么以及何时使用 angular.copy? (深拷贝)
Why and when to use angular.copy? (Deep Copy)
我一直将从服务接收的所有数据直接保存到局部变量、控制器或范围。我想应该被认为是浅拷贝,对吗?
Example:
DataService.callFunction()
.then(function(response) {
$scope.example = response.data;
});
最近我被告知要使用 angular.copy 来创建深拷贝。
$scope.example = angular.copy(response.data);
但是,当我的 Angular 应用程序使用深层复制信息时,它似乎以相同的方式工作。 使用深拷贝 (angular.copy) 有什么特别的好处吗?你能给我解释一下吗?
在这种情况下,您不需要使用 angular.copy()
解释:
=
表示引用,而 angular.copy()
创建一个新对象作为深拷贝。
使用=
意味着改变response.data
的属性会改变$scope.example
对应的属性,反之亦然.
使用 angular.copy()
两个对象将保持分离并且更改不会相互反映。
Javascript传递变量by reference
,这意味着:
var i = [];
var j = i;
i.push( 1 );
现在因为 by reference
部分 i
是 [1],j
也是 [1],即使只更改了 i
。这是因为当我们说 j = i
javascript 不会复制 i
变量并将其分配给 j
而是通过 j
引用 i
变量.
Angular copy 让我们失去了这个引用,这意味着:
var i = [];
var j = angular.copy( i );
i.push( 1 );
现在 i
等于 [1],而 j
仍然等于 []。
在某些情况下,这种 copy
功能非常方便。
我会说angular.copy(source);
在你的情况下是不必要的如果以后你不使用它是没有目的地angular.copy(source, [destination]);
。
If a destination is provided, all of its elements (for arrays)
or properties (for objects) are deleted and then all
elements/properties from the source are copied to it.
将对象或数组的值赋给另一个变量时使用angular.copy,并且不应更改object
值。
没有深层复制或使用angular.copy,更改属性的值或添加任何新的属性 更新引用同一对象的所有对象。
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
<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>
我只是在这里分享我的经验,我使用 angular.copy() 来比较两个对象的属性。我正在处理许多没有表单元素的输入,我想知道如何比较两个对象的属性,并根据结果我必须启用和禁用保存按钮。所以我使用如下。
我将原始服务器对象用户值分配给我的虚拟对象以表示 userCopy 并使用 watch 来检查对用户对象的更改。
我的服务器 API 从服务器获取数据:
var req = {
method: 'GET',
url: 'user/profile/' + id,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
$http(req).success(function(data) {
$scope.user = data;
$scope.userCopy = angular.copy($scope.user);
$scope.btnSts=true;
}).error(function(data) {
$ionicLoading.hide();
});
//initially my save button is disabled because objects are same, once something
//changes I am activating save button
$scope.btnSts = true;
$scope.$watch('user', function(newVal, oldVal) {
console.log($scope.userCopy.name);
if ($scope.userCopy.name !== $scope.user.name || $scope.userCopy.email !== $scope.user.email) {
console.log('Changed');
$scope.btnSts = false;
} else {
console.log('Unchanged');
$scope.btnSts = true;
}
}, true);
我不确定,但是比较两个对象总是让我很头疼,但是使用 angular.copy() 它进行得很顺利。
当使用 angular.copy 时,不是更新引用,而是创建一个新对象并将其分配给目的地(如果提供了目的地)。但还有更多。深拷贝后会发生一件很酷的事情。
假设您有一个工厂服务,其中包含更新工厂变量的方法。
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;
}]);
以及使用此服务的控制器,
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);
}]);
当上面的程序是运行时,输出结果如下,
****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]
因此,使用 angular 副本的妙处在于,目标的引用会随着值的变化而反映出来,而无需再次手动重新分配值。
我知道它已经回答了,但我只是想让它简单点。
所以 angular.copy(data) 你可以在你想要 modify/change 你接收到的对象的情况下使用,方法是保持它的原始值 unmodified/unchanged。
例如: 假设我已经进行了 api 调用并得到了我的 originalObj,现在我想在某些情况下更改 api originalObj 的值但我也想要原始值,所以我可以做的是,我可以在 duplicateObj 中复制我的 api originalObj 并修改 duplicateObj 这样我的 originalObj 值就不会改变。简而言之,与 js obj 的行为不同,duplicateObj 修改不会反映在 originalObj 中。
$scope.originalObj={
fname:'sudarshan',
country:'India'
}
$scope.duplicateObj=angular.copy($scope.originalObj);
console.log('----------originalObj--------------');
console.log($scope.originalObj);
console.log('-----------duplicateObj---------------');
console.log($scope.duplicateObj);
$scope.duplicateObj.fname='SUD';
$scope.duplicateObj.country='USA';
console.log('---------After update-------')
console.log('----------originalObj--------------');
console.log($scope.originalObj);
console.log('-----------duplicateObj---------------');
console.log($scope.duplicateObj);
结果就像....
----------originalObj--------------
manageProfileController.js:1183 {fname: "sudarshan", country: "India"}
manageProfileController.js:1184 -----------duplicateObj---------------
manageProfileController.js:1185 {fname: "sudarshan", country: "India"}
manageProfileController.js:1189 ---------After update-------
manageProfileController.js:1190 ----------originalObj--------------
manageProfileController.js:1191 {fname: "sudarshan", country: "India"}
manageProfileController.js:1192 -----------duplicateObj---------------
manageProfileController.js:1193 {fname: "SUD", country: "USA"}
我一直将从服务接收的所有数据直接保存到局部变量、控制器或范围。我想应该被认为是浅拷贝,对吗?
Example:
DataService.callFunction()
.then(function(response) {
$scope.example = response.data;
});
最近我被告知要使用 angular.copy 来创建深拷贝。
$scope.example = angular.copy(response.data);
但是,当我的 Angular 应用程序使用深层复制信息时,它似乎以相同的方式工作。 使用深拷贝 (angular.copy) 有什么特别的好处吗?你能给我解释一下吗?
在这种情况下,您不需要使用 angular.copy()
解释:
=
表示引用,而angular.copy()
创建一个新对象作为深拷贝。使用
=
意味着改变response.data
的属性会改变$scope.example
对应的属性,反之亦然.使用
angular.copy()
两个对象将保持分离并且更改不会相互反映。
Javascript传递变量by reference
,这意味着:
var i = [];
var j = i;
i.push( 1 );
现在因为 by reference
部分 i
是 [1],j
也是 [1],即使只更改了 i
。这是因为当我们说 j = i
javascript 不会复制 i
变量并将其分配给 j
而是通过 j
引用 i
变量.
Angular copy 让我们失去了这个引用,这意味着:
var i = [];
var j = angular.copy( i );
i.push( 1 );
现在 i
等于 [1],而 j
仍然等于 []。
在某些情况下,这种 copy
功能非常方便。
我会说angular.copy(source);
在你的情况下是不必要的如果以后你不使用它是没有目的地angular.copy(source, [destination]);
。
If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.
将对象或数组的值赋给另一个变量时使用angular.copy,并且不应更改object
值。
没有深层复制或使用angular.copy,更改属性的值或添加任何新的属性 更新引用同一对象的所有对象。
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
<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>
我只是在这里分享我的经验,我使用 angular.copy() 来比较两个对象的属性。我正在处理许多没有表单元素的输入,我想知道如何比较两个对象的属性,并根据结果我必须启用和禁用保存按钮。所以我使用如下。
我将原始服务器对象用户值分配给我的虚拟对象以表示 userCopy 并使用 watch 来检查对用户对象的更改。
我的服务器 API 从服务器获取数据:
var req = {
method: 'GET',
url: 'user/profile/' + id,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
$http(req).success(function(data) {
$scope.user = data;
$scope.userCopy = angular.copy($scope.user);
$scope.btnSts=true;
}).error(function(data) {
$ionicLoading.hide();
});
//initially my save button is disabled because objects are same, once something
//changes I am activating save button
$scope.btnSts = true;
$scope.$watch('user', function(newVal, oldVal) {
console.log($scope.userCopy.name);
if ($scope.userCopy.name !== $scope.user.name || $scope.userCopy.email !== $scope.user.email) {
console.log('Changed');
$scope.btnSts = false;
} else {
console.log('Unchanged');
$scope.btnSts = true;
}
}, true);
我不确定,但是比较两个对象总是让我很头疼,但是使用 angular.copy() 它进行得很顺利。
当使用 angular.copy 时,不是更新引用,而是创建一个新对象并将其分配给目的地(如果提供了目的地)。但还有更多。深拷贝后会发生一件很酷的事情。
假设您有一个工厂服务,其中包含更新工厂变量的方法。
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;
}]);
以及使用此服务的控制器,
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);
}]);
当上面的程序是运行时,输出结果如下,
****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]
因此,使用 angular 副本的妙处在于,目标的引用会随着值的变化而反映出来,而无需再次手动重新分配值。
我知道它已经回答了,但我只是想让它简单点。 所以 angular.copy(data) 你可以在你想要 modify/change 你接收到的对象的情况下使用,方法是保持它的原始值 unmodified/unchanged。
例如: 假设我已经进行了 api 调用并得到了我的 originalObj,现在我想在某些情况下更改 api originalObj 的值但我也想要原始值,所以我可以做的是,我可以在 duplicateObj 中复制我的 api originalObj 并修改 duplicateObj 这样我的 originalObj 值就不会改变。简而言之,与 js obj 的行为不同,duplicateObj 修改不会反映在 originalObj 中。
$scope.originalObj={
fname:'sudarshan',
country:'India'
}
$scope.duplicateObj=angular.copy($scope.originalObj);
console.log('----------originalObj--------------');
console.log($scope.originalObj);
console.log('-----------duplicateObj---------------');
console.log($scope.duplicateObj);
$scope.duplicateObj.fname='SUD';
$scope.duplicateObj.country='USA';
console.log('---------After update-------')
console.log('----------originalObj--------------');
console.log($scope.originalObj);
console.log('-----------duplicateObj---------------');
console.log($scope.duplicateObj);
结果就像....
----------originalObj--------------
manageProfileController.js:1183 {fname: "sudarshan", country: "India"}
manageProfileController.js:1184 -----------duplicateObj---------------
manageProfileController.js:1185 {fname: "sudarshan", country: "India"}
manageProfileController.js:1189 ---------After update-------
manageProfileController.js:1190 ----------originalObj--------------
manageProfileController.js:1191 {fname: "sudarshan", country: "India"}
manageProfileController.js:1192 -----------duplicateObj---------------
manageProfileController.js:1193 {fname: "SUD", country: "USA"}