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
2 Answers
Reset to default 9You 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.