在ngResource上调用$save时,是否可以发布 只有 编辑的字段,而不是每次发布整个模型?

var User = $resource('http://example.com/user/123/');

User.get(function(user) {
  user.name="John Smith";
  user.$save();
  // What I *want* -> POST: /user/123/ {name:'John Smith'}
  // What currently happens -> POST: /user/123/ {name:'John Smith', age: 72, location: 'New York', noOfChildren: 5}
});
有帮助吗?

解决方案

不,这是不可能的,至少不是在实例上,见 http://docs.angularjs.org/api/ngResource.$资源

[...]可以使用以下方法调用类对象或实例对象上的操作方法 参数:

  • HTTP获取"类"操作: Resource.action([parameters], [success], [error])
  • 非获取"类"操作: Resource.action([parameters], postData, [success], [error])
  • 非GET实例操作: instance.$action([parameters], [success], [error])

所以,只有通过将数据传递到"静态"保存方法才能保存,即 User.save.像这样的事情:

User.get(function(user)
{
    user.name = 'John Smith';
    User.save({name: user.name});
});

这是否适合你可能取决于你要做什么 user 实例。

其他提示

当我只想保存一个字段时,我使用静态 .save() 方法,带有一个回调,该回调从该回调中获取响应,并在成功时更新本地对象:

$scope.saveOneField = function(modelInstance) {
  ModelName.save({
    id: modelInstance.id,
    theField: <some value>
  }, function(response) {
    // If you want to update *all* the latest fields:
    angular.copy(response, modelInstance.data);
    // If you want to update just the one:
    modelInstance.theField = response.data.theField;
  });
};

这假设当一个POST请求被发送到资源(即, /modelnames/:id),您的服务器使用modelInstace的最新更新版本进行响应。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top