Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS:使用$timeout递归调用函数时发生RangeError_Javascript_Angularjs - Fatal编程技术网

Javascript AngularJS:使用$timeout递归调用函数时发生RangeError

Javascript AngularJS:使用$timeout递归调用函数时发生RangeError,javascript,angularjs,Javascript,Angularjs,我试图从《从新手到忍者》一书中学习AngularJS。(我以前编程过,但没有使用javascript。) 一个例子是想展示事件。它使用带超时的递归函数调用。当我尝试这段代码时,它给出了一个RangeError:超出了最大调用堆栈大小。没有递归调用,一切都可以工作。我做错了什么 谢谢,彼得 angular.module('myApp.controllers', []); angular.module('myApp.controllers').controller('MessageControll

我试图从《从新手到忍者》一书中学习AngularJS。(我以前编程过,但没有使用javascript。)

一个例子是想展示事件。它使用带超时的递归函数调用。当我尝试这段代码时,它给出了一个RangeError:超出了最大调用堆栈大小。没有递归调用,一切都可以工作。我做错了什么

谢谢,彼得

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');
});