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?
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
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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With