9

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>
Thilak Raj
  • 880
  • 3
  • 10
  • 25

2 Answers2

9

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;
};
Christoph
  • 1,993
  • 1
  • 25
  • 33
2

The fastest option is to edit your $scope.eidtItem and $scope.Cancel functions.

$scope.editItem = function (item) {
    item.editing = true;
    item.oldName = item.name;
}

...

$scope.Cancel = function (item) {
    item.editing = false;
    item.name = item.oldName;
};

http://jsfiddle.net/F7K63/147/

Michał Kolenda
  • 163
  • 1
  • 11
  • I've included a jsfiddle. It should be OK. Please check it. – Michał Kolenda Jan 13 '16 at 09:49
  • @Christoph item.oldName and item.name are Strings, and they are distinct properties of item object. I think it's OK. What problem do you see? You can see item object contents here: http://jsfiddle.net/F7K63/148/ You don't need to use angular.copy to copy single String. – Michał Kolenda Jan 13 '16 at 09:59
  • Yes you're right, with strings it doesn't matters. But i think it should work with all objects ;) – Christoph Jan 13 '16 at 10:10
  • In that case it's clear that we operate on Strings (the value is held in input). So I think using angular.copy is an overkill. – Michał Kolenda Jan 13 '16 at 10:13