【发布时间】:2014-08-25 22:52:41
【问题描述】:
在这种情况下如何防止绑定:
$scope.data = [{i:0, a:0}, {i:0, a:0}, {i:0, a:0}];
$scope.twoofthedata = [$scope.data, $scope.data];
因此 $scope.twoofthedata[0] 独立于 $scope.twoofthedata[1]
【问题讨论】:
在这种情况下如何防止绑定:
$scope.data = [{i:0, a:0}, {i:0, a:0}, {i:0, a:0}];
$scope.twoofthedata = [$scope.data, $scope.data];
因此 $scope.twoofthedata[0] 独立于 $scope.twoofthedata[1]
【问题讨论】:
在 JavaScript 中,对象被操纵by reference。这不是 Angular 绑定问题。
不过,Angular 允许您通过 angular.copy 方法绕过此语言约束,该方法会创建给定对象的深层副本。
$scope.data = [{i:0, a:0}, {i:0, a:0}, {i:0, a:0}];
// Manually call `angular.copy` on each member
$scope.twoofthedata = [
angular.copy($scope.data),
angular.copy($scope.data)
];
// Cleaner version (using `Array.prototype.map`)
$scope.twoofthedata = [$scope.data, $scope.data].map(angular.copy);
但是应该警告您,深拷贝可能非常昂贵,因此只有在真正需要时才使用。
仅供参考:如果您遇到类似问题但未使用 Angular,您可以使用 Lodash,它也有 deep clone method。
【讨论】:
angular.copy($scope.data) > $.extend(true, {}, $scope.data); 现在不显示 RangeError: Maximum call stack size exceeded
$watch 遇到了什么问题?
$.extend也有同样的问题?