3

I'm trying to edit a forms input text field. So the value is loaded from the API and then if you press edit button you can change the value and either cancel the changes or update with the new value you just entered. I try to to store the pre-edited value in a local variable so that I can be able to cancel the changes. Here is my code in the controller.

$scope.preEditFirstName = {};

$scope.edit = function(model) {
    // Copy preedited data locally
    $scope.preEditFirstName = angular.copy(model);
}

$scope.cancelEdit = function(model){
    $scope.model = angular.copy($scope.preEditFirstName);
    console.log($scope.model); //Correct result!
};

And here is the view

<div ng-show="beforeFirstNameEdit">
    {{accountData.firstname || "Loading..."}}
</div>
<div ng-show="!beforeFirstNameEdit">
    <input name="firstName" ng-model="accountData.firstname"  placeholder="First Name" type="text" />
</div>

<div ng-show="beforeFirstNameEdit">
    <button type="button" ng-click="beforeFirstNameEdit = false; edit(accountData.firstname)">Edit</button>
</div>

<div ng-show="!beforeFirstNameEdit">
    <button type="button" ng-click="beforeFirstNameEdit = true; update(accountData.firstname)">Save</button>

    <button type="button" ng-click="beforeFirstNameEdit = true; cancelEdit(accountData.firstname)">Cancel</button>
</div>

At first you just see an "edit" button and when you press it the buttons save and cancel appear. So even if the local variable is correctly saved, when I press the cancel button the field does not show its pre-edit text. How can I fix this?

1 Answer 1

1

In cancelEdit use $scope.accountData.firstname instead of $scope.model

To make it reusable: View:

<button type="button" ng-click="beforeFirstNameEdit = true; cancelEdit('firstname')">Cancel</button>

Controller:

$scope.cancelEdit = function(model){
    $scope.accountData[model] = angular.copy($scope.preEditFirstName);
};

So now cancelEdit will work for all models starting with accountData.*

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

6 Comments

It's the same thing. The function takes the model as an argument.
But you are passing model as argument and updating $scope.model.
Either do $scope[model] = angular.copy... $scope object doesn't have model property.
if the model is accountData.firstname isn't this passed to the cancelEdit() function so in this function $scope.model is the same as $scope.accountData.firstname?
From view you are passing the value of accountData.firstName , but in your function you are expecting it to be property name of scope object?
|

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.