ReferenceError $ timeout未定义angularjs

时间:2016-11-06 19:21:57

标签: javascript angularjs

这里我使用$ timeout在javascript forloop中添加延迟。出乎意料的是,我有一个错误说 ReferenceError $ timeout未定义。我是angularjs的新手,请帮助我。 PLNKR


function CompLibrary() {
  return {
    init: init
  }
  function init(dependencies, controller) {
    dependencies.push(controller);
    angularApp.controller('MainCtrl', dependencies);
  }
}
var compX = CompLibrary();
compX.init(deps, _controller);
function _controller() {
  var ViewModel = this;
  ViewModel.search = "Name";
  ViewModel.quantity = 1;

  for(var i = 0; i < 4; i++) {
    (function(i){ 
        $timeout(function() {
            ViewModel.quantity++;
        }, i * 2000);
    })(i); // Pass in i here
  }

}

2 个答案:

答案 0 :(得分:8)

您必须inject $timeout进入控制器功能。

function _controller($timeout) { ... }

请参阅更新的Plunkr

答案 1 :(得分:-1)

var deps = [];
var angularApp = angular.module('plunker',[]);
function CompLibrary() {
  return {
    init: init
  }
  function init(dependencies, controller) {
    dependencies.push('$timeout');
    dependencies.push(controller);
    angularApp.controller('MainCtrl', dependencies);
  }
}
var compX = CompLibrary();
compX.init(deps, _controller);
function _controller($timeout) {
  var ViewModel = this;
  ViewModel.search = "Name";
  ViewModel.quantity = 1;

  for(var i = 0; i < 4; i++) {
    (function(i){ 
        $timeout(function() {
            ViewModel.quantity++;
        }, i * 2000);
    })(i); // Pass in i here
  }

}

通过在控制器功能中注入$timeout,我们可以解决这个问题。