javascript 使用 AngularJS“copy()”避免引用问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22622449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:28:34  来源:igfitidea点击:

Using AngularJS "copy()" to avoid reference issues

javascriptangularjsangularjs-scope

提问by peter

I'm displaying a list of items, each of which has an "edit"-button next to it. A click on that opens an angular ui modal window and the user can change some properties of the specific item.

我正在显示一个项目列表,每个项目旁边都有一个“编辑”按钮。单击打开一个有角度的 ui 模式窗口,用户可以更改特定项目的某些属性。

Now, what bugged me was that when typing in this edit-window, the specific item in the list of items reflected the changes immediatly. I only wanted it to update when the user clicked 'ok' in the modal, and to not change at all if the user chose 'cancel'.

现在,让我烦恼的是,在此编辑窗口中键入时,项目列表中的特定项目会立即反映更改。我只希望它在用户在模态中单击“确定”时更新,并且如果用户选择“取消”则根本不更改。

My workaround uses copy to make a, well, copy of the chosen item that then serves as model for the view:

我的解决方法是使用 copy 制作所选项目的副本,然后作为视图的模型:

var modalInstance = $modal.open({
    templateUrl: 'scripts/app/views/editBond.html',
    controller: function ($scope, $modalInstance, bond) {
        $scope.bond = angular.copy(bond);
        $scope.ok = function () {
            $modalInstance.close($scope.bond);
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    },
    resolve: {
        bond: function () {
            return bond;
        }
    }
});

Is using angular.copy() appropriate to avoid such issues? Is this a scope issue at all?

使用 angular.copy() 是否适合避免此类问题?这是一个范围问题吗?

采纳答案by Christoph

Yep, using angular.copy()is absolutely appropriate here. If you want something more advanced you might want to checkout angular-history

angular.copy()是的,这里使用绝对合适。如果您想要更高级的东西,您可能需要查看angular-history