最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReferenceError $timeout is not defined angularjs - Stack Overflow

programmeradmin0浏览0评论

Here i add a delay in javascript forloop using $timeout. Unexpectedly i got an error saying
ReferenceError $timeout is not defined. i am new to angularjs please help me. PLNKR


function CompLibrary() {
  return {
    init: init
  }
  function init(dependencies, controller) {
    dependencies.push(controller);
    angularApp.controller('MainCtrl', dependencies);
  }
}
var pX = CompLibrary();
pX.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
  }

}

Here i add a delay in javascript forloop using $timeout. Unexpectedly i got an error saying
ReferenceError $timeout is not defined. i am new to angularjs please help me. PLNKR


function CompLibrary() {
  return {
    init: init
  }
  function init(dependencies, controller) {
    dependencies.push(controller);
    angularApp.controller('MainCtrl', dependencies);
  }
}
var pX = CompLibrary();
pX.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
  }

}
Share Improve this question asked Nov 6, 2016 at 19:21 htonivhtoniv 1,66823 silver badges42 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

You have to inject the $timeout into the controller function.

function _controller($timeout) { ... }

Please see updated Plunkr

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 pX = CompLibrary();
pX.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
  }

}

By injecting $timeout in the controller function we can solve this problem.

发布评论

评论列表(0)

  1. 暂无评论