Angular - save region value to variable, but do not update it when updating region

I have something like this:

$scope.last_good_configuration = $scope.storage; 

In $ scope.last_good_configuration, I keep the last good settings.

And when the user enters an invalid input value, for example, an integer that is too large I want to do:

 $scope.storage = $scope.last_good_configuration; 

But my $ scope.last_good_configuration all the time matches $ scope.storage. How to stop updating $ scope.last_good_configuration? Do I need to somehow evaluate the scope?

+6
source share
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 
+5
source

You can create a new object using angular.copy() , so when you make changes to storage , this will not affect last_good_configuration

 $scope.last_good_configuration = angular.copy($scope.storage); 
+4
source

Since objects are passed by reference, you need to create a new object to store the default configuration. Otherwise, if you change $scope.last_good_configuration it also affects $scope.storage , since both of them point to the same object.

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

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

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

+2
source

Source: https://habr.com/ru/post/986046/


All Articles