简体   繁体   English

变量之间的AngularJS绑定

[英]AngularJS binding between variables

I've got a list of users which I retrieve from my service. 我有一个用户列表,我从我的服务中检索到。 When I select any user I can see and edit info (email, roles, etc) . 当我选择任何用户时,我可以看到并编辑信息(电子邮件,角色等) The problem is that I don't want these changes to affect user's data in the list, I want to update data only after saving (clicking a button). 问题是我不希望这些更改影响列表中的用户数据,我只想在保存(单击按钮)后更新数据。

Now I'm using two variables: 现在我使用两个变量:

$scope.selected - currently selected user $scope.selected - 当前选定的用户
$scope.editable - variable for storing the data I'm editing $scope.editable - 用于存储我正在编辑的数据的变量

And I exchange data like this: 我交换这样的数据:

$scope.initEditable = function () 
{
    $scope.editable = {};
    $.extend($scope.editable, $scope.selected);
}

Looks like a terrible solution. 看起来像一个可怕的解决方案。 What is the proper way to do it? 这样做的正确方法是什么?

Actually, this is the Angular-way of approaching this problem, you are on the right track. 实际上,这是处理这个问题的Angular方式,你走在正确的轨道上。 In scenarios like yours one would typically: 在像你这样的场景中,通常会:

  • Copy an item upon selection (edit start) - this is what you do with editable 选择后复制项目(编辑开始) - 这是您使用editable
  • Have 2-way data binding changing a copy (or an original element) 更改副本(或原始元素)的双向数据绑定
  • Upon edit completion we can propagate changes from a copy to the original 编辑完成后,我们可以将更改从副本传播到原始文件

The nice things about this pattern is that we can easily: 关于这种模式的好处是我们可以轻松地:

  • Offer the 'cancel' functionality where users can revert their changes 提供“取消”功能,用户可以在其中还原其更改
  • Be able to compare a copy and the original and drive parts of the UI based on this comparison (for example, we could disable a 'Save' button if there were no changes) 能够根据此比较比较副本以及UI的原始和驱动部分(例如,如果没有更改,我们可以禁用“保存”按钮)

So, I don't think at all that this approach is terrible. 所以,我根本不认为这种方法很糟糕。 The only suggestion I could have is to use angular's angular.copy method instead of $.extend . 我唯一的建议是使用angular的angular.copy 方法而不是$.extend

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM