Search code examples
angularjstimeoutangular-controller

AngularJS $timeout returning bad request


I am trying to use the $timeout and use the following code within my controller:

     $scope.counter = 0;
        var updateCounter = function() {
            $scope.counter++;
            $timeout(updateCounter, 1000);
        };
            updateCounter();

However, when calling updateCounter(), I get the following error: [https://docs.angularjs.org/error/$http/badreq?p0=function%20()][1]

Thank you very much for any help and input. Steffen


Solution

  • angular
      .module('myApp', [])
      .run(function($rootScope) {
        $rootScope.title = 'myTest Page';
      })
      .controller('testController', ['$scope', '$timeout',
        function($scope, $timeout) {
    
          $scope.counter = 0;
          var updateCounter = function() {
            $scope.counter++;
            $timeout(updateCounter, 1000);
          };
          updateCounter();
        }
      ])
    <!DOCTYPE html>
    <html data-ng-app="myApp">
    
    <head>
      <link rel="stylesheet" href="style.css">
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
      <script src="script.js"></script>
    </head>
    
    <body data-ng-controller="testController">
    
    </body>
    
    </html>

    Your code is working fine for me. you might be forgot to inject $timeout in your controller.