7

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?

1
  • we are missing informations to help you... Commented Apr 27, 2015 at 10:44

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

4

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);

Comments

2

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.