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

标签 javascript object angularjs

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

$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/

相关文章:

javascript - 检查带有原型(prototype)的 native 定义函数

javascript - 停留在一个简单的对象文字范围/引用问题上

javascript - 如何使用 css 在 angular typeahead 中对齐元素

javascript - 根据唯一ID确定是否推送或更新数组中的对象

javascript - 使用 jQuery 交换列表项

javascript - 将 {Object} 的嵌套 [Array] 转换为 > {Object} | JSON文件

javascript - for 循环后返回一个值

javascript - ng-class 中的 AngularJs 多个类

javascript - Angular JS - 指令中的数据绑定(bind)不起作用

javascript - Angularjs中带有按钮的可扩展div