Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editable input text fields in AngularJs do not reset

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?

like image 386
Dimitrios Vythoulkas Avatar asked Mar 03 '26 19:03

Dimitrios Vythoulkas


1 Answers

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.*

like image 131
Avinash Avatar answered Mar 06 '26 08:03

Avinash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!