【发布时间】: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.uservar,如果它在视图的其他地方使用或作为依赖注入;如果我们愿意,也可以将$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