Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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?

like image 647
Yuri Avatar asked Dec 05 '25 10:12

Yuri


1 Answers

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

like image 70
dcodesmith Avatar answered Dec 07 '25 04:12

dcodesmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!