gpt4 book ai didi

javascript - AngularJS - 使用 angular.copy 实现 "undo"失败

转载 作者:行者123 更新时间:2023-11-29 16:14:36 24 4
gpt4 key购买 nike

以下问题:假设我们有一个这样的对象:

$scope.Something = { 'a' : { object... }, 'b' : { another object... } }

这个 Something-object 也在 View 中呈现如下:

<div ng-repeat="s in Something">{{ Something[s].someProperty }}</div>

用户想要编辑Something.a。为此,我们向他展示了一个表格。在显示表单之前,我将当前的 Something.a 保存为一个副本:

$scope.copyForUndo= angular.copy($scope.Something.a);

现在,如果用户点击“取消”,它会得到:

$scope.Something.a = angular.copy($scope.copyForUndo);

但从那以后,这种联想似乎就消失了。不管用户现在对 Something.a 做了什么更改, View 都不会更新。

为什么?

我知道,对象的相等性是什么(例如,那个 { object1: true } != {object1 : true} 但我仍然不明白,为什么它不起作用。

最佳答案

如果你能做到$scope.Something一个数组,然后您可以编辑副本,然后在保存更改时更新数组。它仍然提供撤消,但与您呈现它的方式相反。

在这里摆弄:http://jsfiddle.net/GYeSZ/1/

function MyCtrl($scope) {
$scope.Something = [
{ name: "Aye", desc: new Date() },
{ name: "Bee", desc: new Date() },
{ name: "See", desc: new Date() }
];

$scope.edit = function(idx) {
$scope.copy = angular.copy($scope.Something[idx]);
$scope.idx = idx;
}

$scope.save = function() {
$scope.Something[$scope.idx] = angular.copy($scope.copy);
$scope.cancel();
}

$scope.cancel = function() {
$scope.copy = null;
$scope.idx = -1;
}
}

更新ng-repeat 有另一种语法可用于枚举字典以获取其 key 。使用此语法,您可以使用问题中描述的数据结构

在这里摆弄:http://jsfiddle.net/GYeSZ/3/

function MyCtrl($scope) {

$scope.edit = function(key) {
$scope.copy = angular.copy($scope.Something[key]);
$scope.key = key;
}

$scope.Something = {
"a": { name: "Aye", desc: new Date() },
"b": { name: "Bee", desc: new Date() },
"c": { name: "See", desc: new Date() }
};

$scope.save = function() {
$scope.Something[$scope.key] = angular.copy($scope.copy);
$scope.cancel();
}

$scope.cancel = function() {
$scope.copy = null;
$scope.key = null;
}
}

HTML

<div ng-repeat="(key, value) in Something" ....>

关于javascript - AngularJS - 使用 angular.copy 实现 "undo"失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18840992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com