Javascript AngularJS:使用$timeout递归调用函数时发生RangeError
我试图从《从新手到忍者》一书中学习AngularJS。(我以前编程过,但没有使用javascript。) 一个例子是想展示事件。它使用带超时的递归函数调用。当我尝试这段代码时,它给出了一个RangeError:超出了最大调用堆栈大小。没有递归调用,一切都可以工作。我做错了什么 谢谢,彼得Javascript AngularJS:使用$timeout递归调用函数时发生RangeError,javascript,angularjs,Javascript,Angularjs,我试图从《从新手到忍者》一书中学习AngularJS。(我以前编程过,但没有使用javascript。) 一个例子是想展示事件。它使用带超时的递归函数调用。当我尝试这段代码时,它给出了一个RangeError:超出了最大调用堆栈大小。没有递归调用,一切都可以工作。我做错了什么 谢谢,彼得 angular.module('myApp.controllers', []); angular.module('myApp.controllers').controller('MessageControll
angular.module('myApp.controllers', []);
angular.module('myApp.controllers').controller('MessageController', function($scope, $timeout) {
$scope.messages = [{
sender: 'user1',
text: 'Message1'
}];
var timer;
var count = 1;
$scope.loadMessages = function() {
++count;
$scope.messages.push({
sender: 'user1',
text: 'Message'+count
});
// This line seems to cause the problem
timer = $timeout($scope.loadMessages(), 2000);
if (count==3) {
$scope.$broadcast('EVENT_NO_DATA', 'Not Connected');
$timeout.cancel(timer);
}
};
timer = $timeout($scope.loadMessages(), 2000);
$scope.$on('EVENT_RECEIVED', function(){
console.log('Received emitted event EVENT_RECEIVED in MessageController.');
});
}))
})) 将
$scope.loadMessages()
更改为$scope.loadMessages
angular.module('myApp.controllers').controller('StatusController', function($scope) {
$scope.name = 'World';
$scope.status = 'Connected';
$scope.statusColor = 'green';
$scope.$on('EVENT_NO_DATA', function(event, data) {
console.log('Received broadcast event EVENT_NO_DATA in StatusController.');
$scope.status = data;
$scope.statusColor = 'red';
$scope.$emit('EVENT_RECEIVED');
});