我希望能够判断 $resource 实例是否已被用户修改 - 也就是说,它的当前状态是否与最初从服务器加载的状态不同 && 尚未 $saved。我怎样才能做到这一点?
3 回答
假设您获得了一个资源,然后将其放在当前 $scope 上,以便用户可以对其进行编辑:
$scope.question = Questions.get({id:"19615328"});
然后,您可以观察它的变化,如下所示:
// 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);
(这里的几乎所有内容都是下面聊天中额外问题的结果)
然后,每当您想检查它是否已更改时,$scope.userChange
都可以告诉您是否发生了更改。当你保存对象时,重置$scope.userChange
.
你甚至可以这样做
$scope.$watch('question', function() {
$scope.question.$save();
}, true);
显然,您需要添加某种油门或“去抖动”系统,因此它会等待一秒钟左右,一旦您将其放置到位,对对象的任何更改都会导致通过$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);
您甚至可以结束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;
};
然后,无论何时您调用Questions.getAndAutosave
,它返回的任何内容都已被监视,并将自动执行$save
。我们这样做的原因if (newValue === oldValue) return;
是因为$watch
一旦你调用它就会触发,然后观察变化。我们不需要在第一次通话时保存。
I've found a solution that both does not treat downloading data from server as user change and is implemented directly in the service itself. It might not be the most efficient solution possible, but provides exactly the functionality I want,
app.factory('testService', ['$resource', '$rootScope', function($resource, $rootScope){
var test = $resource('/api/words/:id', {id: '@id'});
test.orig_get = test.get;
test.get = function(options){
var instance = test.orig_get(options, function(){
instance.unsaved = false;
$rootScope.$watch(function(){
return instance;
}, function(newValue, oldValue) {
if(angular.equals(newValue, oldValue)){
return;
}
var changed_indexes = [];
for(var i in newValue){
if(!angular.equals(newValue[i], oldValue[i])){
changed_indexes.push(i);
}
}
if(newValue != null && oldValue != null && !(changed_indexes.length==1 && changed_indexes[0]=='unsaved')){
console.log('detected change. setting unsaved to true');
instance.unsaved = true;
}
}, true);
});
return instance;
}
test.prototype.orig_save = test.prototype.$save;
test.prototype.$save = function(options){
return this.orig_save(options, function(){
this.unsaved = false;
})
}
return test;
}]);
您可以克隆初始对象,然后在需要检查时进行比较。
master = null
resource = Resource.get({id:1}, function() {
master = angular.copy(resource)
})
function isModified() {
return !angular.equals(resource, master)
}