AngularJS:使用$ timeout递归调用函数时的RangeError

时间:2016-01-27 12:45:42

标签: javascript angularjs

我正在尝试从新手到忍者的书#AngularJS中学习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.');
});

});

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

});

1 个答案:

答案 0 :(得分:0)

$scope.loadMessages()更改为$scope.loadMessages