Reputation: 1668
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 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
}
}
Upvotes: 2
Views: 8466
Reputation: 1668
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
}
}
By injecting $timeout
in the controller function we can solve this problem.
Upvotes: -2
Reputation: 3820
You have to inject
the $timeout
into the controller function.
function _controller($timeout) { ... }
Please see updated Plunkr
Upvotes: 9