这是我如何实现这一点的最佳示例。我假设了一些关于你的控制器和工厂的东西。请注意,您需要将 $q 注入您的工厂以使用延迟。这就是我在我的应用程序中的做法。
http://jsfiddle.net/JimTheDev/2zLEp/
/*
NOTE: make sure to inject $q into your factory before
this. For the purposes of my example, let's assume your
factory looks like this:
*/
app.factory('mySweetFactory', ['$q', function($q) {
return {
// You probably have a bunch of other methods like
// this one in your factory.
myothermethod: function(argument1, argument2) {
/* some code here */
},
update: function (staffList) {
// Create a new deferred object
var deferred = $q.defer();
// get local last updated timestamp
var lastUpdatedLocal = "";
for (i=0; i < staffList.length; i++) {
// get largest (most recent) timestamp
if(staffList[i].entry_date > lastUpdatedLocal) {
lastUpdatedLocal = staffList[i].entry_date;
}
}
// Make a call to the remote api
$http.get('REMOTE_API_CALL').then(function(response) {
// Get the remote last updated
// time from the response
var lastUpdatedRemote = response.data[0].entry_date;
// Check if local or remote is larger
// You probably need to modify this
// depending on your datetime formatting.
// I am assuming an epoch string.
if(lastUpdatedRemote > lastUpdatedLocal)
{
// Resolve the deferred and return
// the data so that the controller can
// use it to update the view
deferred.resolve(response.data);
} else {
// Since we don't need to do anything,
// reject the deferred
deferred.reject();
});
// Return the promise from the deferred object
// immediately. We will eventually either
// resolve or reject it, but at the start, it
// will be in a pending state.
return deferred.promise;
}
};
}]);
app.controller('mySweetController', ['mySweetFactory', function(mySweetFactory){
$scope.doUpdate = function() {
mySweetFactory.update($scope.staffList).then(function(newStaffList) {
// Promise was resolved. List needs updating!
$scope.staffList = newStaffList;
}, function(){
// Promise was rejected. No update needed!
});
};
}]);