如何将范围的深层复制到一个不跟踪原始范围变化的新范围?

时间:2015-04-23 11:03:34

标签: angularjs

我使用的是Angular JS,我有两个范围

$scope.selected = {
    ids: []
};

$scope.copy = {
    ids: []
};

当我点击一个按钮时,我希望$scope.copy$scope.selected获取元素,所以我这样做了

<button ng-click="copy=selected">copy</button>

这部分工作但现在每次我更改所选的值时,副本的值也会改变。 我也尝试过使用某个功能,但它并没有解决我的问题。

$scope.copylist = function(selected) {
    $scope.copy.ids.push(selected.ids.valueOf());
}

如果更新原始范围的值时,如何制作不会更新的副本?

1 个答案:

答案 0 :(得分:5)

使用angular.copy应该做的伎俩

<button ng-click="copyScope()">copy</button>

function copyScope () {
    $scope.copy = angular.copy($scope.selected);
}

代码说明

<强> HTML

<div ng-app="myApp" ng-controller="myController">
    <button ng-click="copyOriginal()">copyOriginal</button>
    <button ng-click="touchOriginal()">touchOriginal</button>
    <pre> {{original}} </pre>
    <pre> {{copy}} </pre>
</div>

<强> JS

$scope.original = [1, 2, 3];
$scope.copy = [];

$scope.touchOriginal = function () {
    $scope.original.push(4);
};

$scope.copyOriginal = function () {
    $scope.copy = angular.copy($scope.original);
    console.log($scope.copy);
}

$scope.$watch('copy', function (newCopy, oldCopy) {
    // Nothing should happen here when you trigger `touchOriginal()`
    console.log(newCopy, oldCopy);
});

<强> JSFIDDLE