Angularjs:在服务器端更新失败后,在$watch中恢复模型值

前端之家收集整理的这篇文章主要介绍了Angularjs:在服务器端更新失败后,在$watch中恢复模型值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是场景:

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.但是如果由于某种原因(连接问题,服务器错误,无效会话,权限不足,.etc)更新失败,我想将该值恢复到以前的版本.在小提琴中你可以看到如果选择“拒绝延迟”并尝试更改值会发生什么 – 它会启动失败请求,恢复值和$watch触发器的infinte循环.

目前我正在范围上设置一个标志,表明请求已失败,下一个$watch不应该调用该服务.但我正在寻找减少这种样板代码方法.

当然,我总是可以使用其他一些方法通知范围,例如ng-change,但后来我失去了对旧值的引用.我可以在我的范围内保留参考,但这比当前情况更糟糕.

您有任何想法应该如何处理这些情况?基本上我正在寻找的是一种更新$watch中的模型而不会触发更多$watch的方法,如果可能的话.

解决方法

使用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相关文章