我将数据存储在scope变量中,如下所示
$scope.myData =
{
"firstName": "rocky",
"lastName": "P",
"place": "Koraput",
"education": [
{
"id": "764006"
},
{
"id": "764001"
}
],
"email": "rockyp123@gmail.com",
"id": "46ads75asda7s6d57ad"
}案例:假设我正在更新这个数据。我将教育添加到其中,然后单击cancel。如何在单击cancel时删除当前添加的教育,并在单击edit user时检索上面提到的仅为两个教育的数据
发布于 2017-04-27 14:41:45
您应该保留两个单独的对象,一个是原始的、未更改的对象,另一个用于编辑。一旦用户点击,比如说save,你才应该用第二个对象覆盖第一个对象。单击cancel后,您可以简单地将可编辑对象的值恢复为原始数据的克隆。
首先,将第一个对象克隆到新的第二个对象中:
// Your original data (unchanged)
$scope.myData = { /* ... */ };
// Your object for editing purposes
$scope.myDataClone = clone($scope.myData);
$scope.cancel = function() {
// reset the 'editable' clone to the unchanged value of myData
$scope.myDataClone = clone($scope.myData);
}
$scope.save = function() {
// Once the user accepts their changes, you can simply
// set the value of myData to a clone of the edited data.
// This will ensure you are not just creating a new pointer
// from myData to myDataClone, which would cause myData
// to change if you make subsequent requests to myDataClone.
$scope.myData = clone($scope.myDataClone);
}
// A clone function which takes an object and returns an exact
// replica as a new object with a unique memory reference
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}发布于 2017-04-27 14:39:18
您可以使用angular.copy()方法来复制原始数组的对象,并在取消时引用它
var app = angular.module('demoApp', []);
app.controller('demoCtrl', function($scope) {
$scope.myData = {
"firstName": "rocky",
"lastName": "P",
"place": "Koraput",
"education": [{
"id": "764006"
}, {
"id": "764001"
}],
"email": "rockyp123@gmail.com",
"id": "46ads75asda7s6d57ad"
};
$scope.copy = angular.copy($scope.myData.education);
$scope.onAdd = function() {
$scope.myData.education.push({
id: $scope.myData.education.length
});
};
$scope.onCancel = function() {
$scope.myData.education = $scope.copy; // <----reset to original
};
});<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="demoCtrl">
<pre>{{myData.education}}</pre>
<button ng-click="onAdd()">+</button>
<button ng-click="onCancel()">X</button>
</div>
发布于 2017-04-27 14:43:04
使用id删除
$scope.myData =
{
"firstName": "rocky",
"lastName": "P",
"place": "Koraput",
"education": [
{
"id": "764006"
},
{
"id": "764001"
}
],
"email": "rockyp123@gmail.com",
"id": "46ads75asda7s6d57ad"
};
//Remove specific item
$scope.onCancel = function(cancelId){
for(var i in $scope.myData.education){
if($scope.myData.education[i].id==cancelId){
$scope.myData.education.splice(i, 1);;
break;
}
}
};https://stackoverflow.com/questions/43650198
复制相似问题