Reputation: 530
I have this site which is basically a server-monitor for a small game called "Armagetron Advanced". This server-monitor is supposed to reload the json every time I come back to the site.
Here's the code for my app:
controller('ServerBrowserController', function($scope, ServerDataFactory) {
$scope.loadServers = function() {
$scope.ServerData = ServerDataFactory.getServerDataWithQ();
//promise.then(function(data) {
//$scope.$apply(function() {
//$scope.ServerData = data;
//});
//});
}
document.addEventListener(visibilityChange, function() {
if(document[hidden] == false) {
$scope.loadServers();
}
}, false);
$scope.loadServers();
}).
factory('ServerDataFactory', function($http, $q) {
var deferred = $q.defer();
var factory = {};
factory.getServerDataWithQ = function() {
$http({ method: 'GET', url: '/new/app/serverxml_to_json.php' }).
success(function(data) {
deferred.resolve(data);
}).
error(function(data) {
alert("Couldn't load xml data.");
});
return deferred.promise;
};
return factory;
}).
The http query works fine the first time, but as soon I come back to the site and the php script is queried again, the bindings aren't updated, even though the data is different. I thought this would automatically work as promises internally call $apply on the scope, but apparently it doesn't. Hence I tried to call $apply manually:
$scope.$apply(function() {
$scope.ServerData = data;
}
But that also didn't work because now it said that "$digest [is] already in progress". The weird thing was tho, I didn't even work on the first try, which it used to do without the $apply. After doing some research on the digest problem, one of the solutions suggested trying the following:
$scope.$$phase == "$digest" || $scope.$apply(function() {
$scope.ServerData = data;
}
But that also didn't work because $scope.$$phase was always set to "$digest", no matter if it was the initial data loading or the n-th time.
Upvotes: 0
Views: 67
Reputation: 8976
You create a deferred
object in ServerDataFactory, so every call to getServerDataWithQ
tries to resolve the same deferred, but a deferred can be resolved only once. So it's a simple fix: move var deferred = $q.defer();
into getServerDataWithQ()
.
Upvotes: 1