简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM