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.

1 Answer 1

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

2 Comments

I see. Thank you. And in that save function, do you just enumerate the values, like a line of code per form input?
Yes, that would be the simplest way.

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.