这是场景:
fiddle :
$scope.$watch('obj.value',function(val, oldVal) {
if (val === oldVal) return;
MyService.update($scope.obj, $scope.result).then(function(response){
$scope.results.push(response);
}, function(response) {
$scope.obj.value = oldVal;
$scope.results.push(response);
});
});
我在一个值上设置了一个监视,并在它发生变化时将其更新为 db。但是如果由于某种原因更新失败(连接问题、服务器错误、无效 session 、权限不足等),我想将该值恢复到以前的版本。在 fiddle 中,您可以看到如果您选择“拒绝延迟”并尝试更改值会发生什么 - 它会启动失败请求、恢复值和 $watch 触发器的无限循环。
目前,我正在作用域上设置一个标志,以指示请求已失败,下一个 $watch 不应调用该服务。但我正在寻找减少这种样板代码的方法。
当然,我总是可以使用其他一些方法来通知范围,例如 ng-change,但是我失去了对旧值的引用。我可以将引用保留在我的范围内,但这比当前情况更糟。
你有什么想法应该如何处理这些情况吗?基本上我正在寻找的是一种更新 $watch 中的模型而不触发更多 $watches 的方法,如果这可能的话。
最佳答案
使用 ng-change 指令代替观察者,并使用内部状态变量来存储最后一次成功保存的值。
看看它在行动:http://jsfiddle.net/Zmetser/vscGP/6/
function MyCtrl($scope, MyService) {
var lastSaved;
$scope.obj = {value: "foo"};
$scope.results = [];
$scope.result = "1";
lastSaved = $scope.obj.value;
$scope.sentinel = function ( value ) {
MyService.update($scope.obj, $scope.result).then(function(response){
lastSaved = angular.copy($scope.obj.value);
$scope.results.push(response);
}, function(response) {
if ( lastSaved )
$scope.obj.value = lastSaved;
$scope.results.push(response);
});
};
}
<input type="text" ng-model="obj.value" ng-change="sentinel(obj.value)"/>
关于Angularjs:在服务器端更新失败后恢复 $watch 中的模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16915984/