【问题标题】:AngularJS: What is the correct approach to update a resourceAngularJS:更新资源的正确方法是什么
【发布时间】:2015-01-12 13:04:22
【问题描述】:

我想知道更新资源的最佳方法是什么。

最佳我的意思是最常见的实现、可测试并且专注于 AngularJS 标准。根据您的经验,您更喜欢什么。

以下是我正在考虑的一些案例。

方法一:简单的方法

var $scope.user = User.get({ id: 123 });
// get this object in a view form, change some stuffs, NOT all of them

$scope.doUpdate = function() {
  $scope.user.$update();
}
  • 优点:很容易写
  • 缺点:如果属性很多,只修改了一个,则全部重发

方法二:复制

var $scope.user = User.get({ id: 123 });
var $scope.userCopy = angular.copy($scope.user);
// get this object in a view form, change some stuffs, NOT all of them

$scope.doUpdate = function() {
  $scope.userCopy.$update();
}
  • 优势:保护$scope.user var,如果它在视图的其他地方使用或作为依赖注入;如果我们愿意,也可以将$scope.userCopy 还原为$scope.user
  • 缺点:变量重复和$scope.user不会反映变化。

方法3:非常安全的一种

var user = User.get({ id: 123 });
var $scope.userCopy = angular.copy(user);
// get this object in a view form, change some stuffs, NOT all of them

$scope.doUpdate = function() {
  var userChanged = new User();
  userChanged.id = user.id;
  if ($scope.userCopy.name !== user.name) {
    userChanged.name = $scope.userCopy.name;
  }
  if ($scope.userCopy.surname !== user.surname) {
    userChanged.surname = $scope.userCopy.surname;
  }
  // and iterate on all the values we are expected to be modified
  userChanged.$update();
}
  • 优势:您确切知道自己更新了什么
  • 缺点:可能意味着大量代码和检查,变量重复和$scope 不会反映更改。

【问题讨论】:

  • 不同情况不同方法...没有one-size-fits-all

标签: javascript angularjs ngresource


【解决方案1】:

我使用方法 3 的变体来进行部分更新,当然Lo-Dash 可以提供帮助,我想确保我只 PUT 更新的字段,仅此而已。

我定义了一个 diff 函数来选择需要发送到服务器的部分:

var diff = function(newVal, oldVal){
    return _.omit(newVal , function(value, key){
        return angular.equals(oldVal[key] , value);
    });
}

在加载表单之前,我有一份当前模型的副本:

var oldVal = angular.copy($scope.user);

那么实际的更新会是这样的:

$scope.doUpdate = function(){
    var userPartial = diff($scope.user , oldVal);
    User.update({id: $scope.user._id} , userPartial);
}

如果用户点击取消按钮,或者更新过程中出现问题,您可以随时恢复到 oldVal。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2018-08-16
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多