3

Is it possible to reset a form to it's initial values in AngularJS?

I have a simple form with a field with ng-model='my_object.my_value', which is disabled. When I start editing it, I copy $scope.my_object to $scope.my_object_backup.

If I click cancel, I disable the field and set $scope.my_object = $scope.my_object_backup. But the value I see in my input doesn't change.

Is there a way to got around this behavior?

I tried setting value="{{my_object.my_value}}" but it doesn't change anything.

3
  • 1
    how did you copy the object? Commented Aug 8, 2013 at 20:06
  • Basically the exact same question: stackoverflow.com/questions/13085024/… Commented Aug 8, 2013 at 20:08
  • I did a simple $scope.my_object_backup = $scope.my_object Commented Aug 8, 2013 at 20:09

1 Answer 1

7

You can use angular.copy to deep copy the object

$scope.my_object_backup = {};
angular.copy($scope.my_object, $scope.my_object_backup);

What you did $scope.my_object_backup = $scope.my_object is make reference assignment so they actually point to the exacly same object. So, if you modify via one reference, you will access to the modified object via the other reference.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I tried this first (like in the docs) but it always reset to null so I thought it was not good and went with $scope.my_object_backup = $scope.my_object... I tried again like you said, and noticed my $scope.my_object_backup was initialized with null... I changed it to new Object() and it works like a charm!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.