角度资源 - 如何检查资源实例是否有任何未保存的更改?

Kub*_*lik 12 javascript angularjs angularjs-service angularjs-resource

我希望能够判断用户是否修改了$ resource实例 - 也就是说,它的当前状态是否与最初从服务器加载的状态不同&&尚未保存.我怎样才能做到这一点?

Phi*_*ret 14

假设您获得了一个资源,然后将其放在当前的$ scope上,以便用户可以编辑它:

$scope.question = Questions.get({id:"19615328"});
Run Code Online (Sandbox Code Playgroud)

然后,您可以观看此类更改:

// some flag, name it anything
$scope.userChange = false;
$scope.$watch('question', function(newValue, oldValue) {
    if(newValue && newValue != oldValue){
        $scope.userChange = true;
        // if you want to you can even do this, this will trigger on every change though
        $scope.question.$save();
    }
}, true);
Run Code Online (Sandbox Code Playgroud)

(几乎所有来自此处的内容都是下面聊天中额外问题的结果)

然后,只要您想检查它是否已更改,$scope.userChange就可以告诉您是否发生了更改.当您保存对象时,重置$scope.userChange.

你甚至可以这样做

$scope.$watch('question', function() {
    $scope.question.$save();
}, true);
Run Code Online (Sandbox Code Playgroud)

显然你想添加某种油门或"去抖"系统,所以它等待一秒左右,一旦你有了这个,对对象的任何改变都会导致保存$scope.$watch.

如果你想检查null,当你还没有收到实际对象时.

$scope.$watch('question', function(newValue, oldValue) {
    // dont save if question was removed, or just loaded
    if(newValue != null && oldValue != null){
        $scope.question.$save();
    }
}, true);
Run Code Online (Sandbox Code Playgroud)

您甚至可以Questions.get打电话,查看这些问题,以获得有关如何在服务和工厂级别执行此操作的答案,以执行此类操作.

Questions.getAndAutosave = function(options){
    var instance = Questions.get(options);
    $scope.$watch(function(){
            return instance;
        },
        function(newValue, oldValue){
            if (newValue === oldValue) return;
            if(newValue != null && oldValue != null){
                instance.$save();
            }
        }, true);
    return instance;
};
Run Code Online (Sandbox Code Playgroud)

然后Questions.getAndAutosave,无论何时你打电话,无论它返回的是什么都已经被观看,并且将自动进行$save.我们这样做的原因if (newValue === oldValue) return;是因为$watch一旦你打电话就会发火,然后注意变化.我们不需要保存第一个电话.