无法在angularJS应用程序中向控制器注入$ timeout

时间:2016-02-22 13:08:33

标签: javascript angularjs dependency-injection

我是Angular JS的新手。目前正在开发游戏。其中一个需求是在超时时调用函数。在进行研究时,我发现$timeout提供了AngularJS,我必须将$timeout注入控制器,我正在尝试这样做。但出于某种原因,我不确定它似乎不起作用!或者我不知道如何调试?

 var ObstacleApp = angular.module('ObstacleApp', [])
 .controller('GameCtrl',function($scope,$timeout,game) {
 $scope.game = game;
 });

 ObstacleApp.factory('game', function() {
 var tileNames = ['true', 'false', 'true', 'false', 'true','true','true','false','true','true','true','false','true','true','true','true','true','true','true','true'];

 return new Game(tileNames);
 });


  function Game(tileNames)
  {
     // omitted code

     this.showOnClick = function()
     {
       // omitted code

       $timeout(callOnTimeout,6000);
     }
  }

修改: 我做了@STEVER提到的改变 - 但它似乎不起作用 当我Inspect控制台时,我看到了

Error: Unknown provider: $timeoutProvider <- $timeout
at Error (native)
at file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:2492:15
at Object.getService [as get] (file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:2620:39)
at file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:2497:45
at getService (file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:2620:39)
at invoke (file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:2650:13)
at Object.instantiate (file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:2677:23)
at file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:4354:24
at file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:3986:17
at forEach (file:///home/rakshith/Desktop/Obstaclegame/lib/angular/angular.js:118:20)(anonymous function) @ angular.js:5240

2 个答案:

答案 0 :(得分:0)

您忘记将$timeout注入您的工厂:

ObstacleApp.factory('game', function($timeout) {

答案 1 :(得分:0)

 ObstacleApp.factory('game', function($timeout) {
    //...
    return new Game(tileNames, $timeout);
 });


  function Game(tileNames, $timeout)
  {
     // omitted code

     this.showOnClick = function()
     {
       // omitted code

       $timeout(callOnTimeout,6000);
     }
  }