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.

Samuel Bolduc
  • 18,163
  • 7
  • 34
  • 55

1 Answers1

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.

zs2020
  • 53,766
  • 29
  • 154
  • 219
  • 2
    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! – Samuel Bolduc Aug 08 '13 at 20:18