Yuri
Yuri

Reputation: 447

How to do a deep copy of a scope into a new one that doesn't track the changes of the original scope?

I'm using Angular JS and I have two scopes

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

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

when I click a button I want $scope.copy to get the elements from $scope.selected so I did this

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

this works in part but now each time I change the values of selected, the values of copy change too. I've also tried using a function but it didn't solve my problem.

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

How would I make a copy that doesn't update when the values from the original scope are updated?

Upvotes: 3

Views: 751

Answers (1)

dcodesmith
dcodesmith

Reputation: 9614

Using angular.copy should do the trick

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

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

Code Explanation

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

Upvotes: 5

Related Questions