0

This seems like a dumb question, but I'm new to web/angular programming don't even know how to google it. If I have a model that the user can edit with a form, how do I let the user cancel the edit?

Do I backup the old values before the edit, or do I create a copy of the model and let the user edit that? In the first case, if the user cancels the edit, I guess I have to copy the backed-up values back over the changed model? In the second case, if the user accepts the edits, I'll have a new copy of the model that's been changed. Other parts of the model that point to it will need to be updated.

In pseudo-code:

foo->bar  // foo is a bigger model and user wants to edit bar
barCopy = bar.copy();  // I realize copy() is not-so-trivial thing
open a form on bar
if edits are cancelled, bar needs to be updated with barCopy

or

open a form on barCopy
if edits are accepted, foo (and others) is pointing at an out of date bar

Is there a better option than either of these? If not, is there a convention about which one to do in angular? I don't see a good way to do the copying at the language level - googling this topic yields a lot of discussion and this very up-voted answer. It's troubling that this basic thing I need to do contains so much weird science. It makes me think there must be a simpler way.

Community
  • 1
  • 1
goodson
  • 727
  • 2
  • 14
  • 24

1 Answers1

1

Typically, in my controllers that contain form input I have a model for the form inputs themselves, and when a user 'saves', then I update the actual model (and persist in the background). So:

$scope.viewModel = {
   myModel: {name:'test'},
   formInputs: {nameInput: ''}
};

$scope.edit = function(){
   $scope.viewModel.formInputs.nameInput = $scope.viewModel.myModel.name;
}

$scope.save = function(){
   $scope.viewModel.myModel.name = $scope.viewModel.formInputs.nameInput;
}

$scope.cancelEdit = function(){
   $scope.viewModel.formInputs.nameInput = '';
}
Andrew Church
  • 1,391
  • 11
  • 13