This is because Movie.query()
calls $scope.$apply()
after it gets response from the server.
Everytime $scope.$apply()
is called, angular does dirty checking (which again invokes test
and therefore calls Movie.query()
again) to find out if anything has changed. This causes an infinite loop.
move Movie.query()
out from the test()
, and this should work.
Let me make myself clear - take look at this pseudo code:
var watches = ['$scope.test()'];
var previous = {};
var values = {};
$rootScope.$apply = function(){
previous = values;
values = {};
var dirty = false;
for (var i =0;i<watches.length;i++){
var expression = watches[i];
values[expression] = value = eval(expression);
if(value!=previous)dirty=true;
}
if(dirty)$rootScope.$apply();
}
Movie.query = function(){
setTimeout(function(){
$rootScope.$apply();
},300);
}
$scope.test = function(){
Movie.query();
return 42;
}
so the flow is following:
- $scope.apply();
- $scope.test();
- Movie.query(); ->
setTimeout($scope.apply,100)
(back to beginning );
and so on..