How to implement the cancel button for edit functionality in angularjs

Thilak Raj picture Thilak Raj · Jan 13, 2016 · Viewed 9.4k times · Source

i have used edit button. after editing i have save and cancel button .save button is working as i expected but not the cancel button. if i click the cancel button after trying to edit, it should show the previous text. can anyone please help me
js fiddle here http://jsfiddle.net/F7K63/143/

 <tr ng-repeat="item in items">
        <td>
            <span ng-hide="item.editing">{{item.name}} <button  ng-click="editItem(item)">Edit</button></span>
            <input ng-show="item.editing" ng-model="item.name"  autofocus />
            <button ng-show="item.editing" ng-click="doneEditing(item)">Save</button>
             <button ng-show="item.editing" ng-click="Cancel(item)">Cancel</button>
        </td>
    </tr>

Answer

Christoph picture Christoph · Jan 13, 2016

Make a copy of your object you want to edit. If you press cancel replace the origin. See the fiddle

$scope.editItem = function (item) {
    item.editing = true;
    item.backupName = angular.copy(item.name);
}

$scope.doneEditing = function (item) {
    item.editing = false;
    delete item.backupName;
    //do some background ajax calling for persistence...
};
$scope.Cancel = function (item) {
    item.editing = false;
    item.name = angular.copy(item.backupName);
    delete item.backupName;
};