Angular JS and Directive Link and $timeout Angular JS and Directive Link and $timeout javascript javascript

Angular JS and Directive Link and $timeout


You can inject dependencies to the directive like in other modules:

.directive('myDirective', ['$timeout', function($timeout) {   return {        ...        link: function($scope, element){            //use $timeout        }    };}]);


In your code your comment says 'show only one "pass"'. Timeout only executes one time, after the specified, delay.

Perhaps you want setInterval (if you're pre angular 1.2)/ $interval (new to 1.2) which sets up a recurring call. Here's the setInterval version:

var timeout = setInterval(function(){    // do stuff    $scope.$apply();}, 2000); 

I included $apply as a reminder that since this is an external jQuery call you need to tell angular to update the DOM (if you make any appropriate changes). ($timeout being an angular version automatically updates the DOM)


Not sure if I got your doubt here, but $timeout is pretty much the same thing as javascript plain setTimeout function, and it is supposed run only once, as opposed as setInterval.

If you're using Angular 1.2.0, change $timeout service per $interval. If otherwise you're on 1.0 version, you can make it recursive:

var timeout;var update = function() {  // clear previous interval  timeout && timeout();  timeout = $timeout(function() {    // drawSomething(...);    update();  }, 2000);}