Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - save scope value to variable, but not update it when scope updates

I have something like this:

$scope.last_good_configuration = $scope.storage;

In $scope.last_good_configuration I keep last good settings.

And when user type in input bad value, for example too big integer i want to do:

$scope.storage = $scope.last_good_configuration;

But my $scope.last_good_configuration is all the time the same as $scope.storage. How to stop updating $scope.last_good_configuration? I have to evaluate my scope somehow?

like image 382
Blejwi Avatar asked Apr 27 '15 10:04

Blejwi


3 Answers

You need to make a copy or clone of the original object. Angular has a built in method for this: angular.copy.

$scope.last_good_configuration = angular.copy($scope.storage);


//Edits must be at least 6 characters workaround
like image 199
Chris Charles Avatar answered Oct 22 '22 02:10

Chris Charles


You can create a new object using angular.copy() so when you make changes to storage it won't affect last_good_configuration

$scope.last_good_configuration = angular.copy($scope.storage);
like image 4
Satpal Avatar answered Oct 22 '22 03:10

Satpal


Since objects are passed by reference, you need to create a new object to store default configuration in. Otherwise, when you modify $scope.last_good_configuration it also affects $scope.storage since they both point to the same object.

Use angular.extend method which will copy all properties from $scope.storage into the new object {}:

$scope.last_good_configuration = angular.extend({}, $scope.storage);

UPD. I totally forgot about dedicated angular.copy which is probably more appropriate in this case, especially is $scope.storage has nested object structure: angualar.extend will make a shallow copy, in this case you should use angular.copy (see Satpal answer).

like image 2
dfsq Avatar answered Oct 22 '22 03:10

dfsq