How do I use $timeout service in a Directive?
link
function isn't a correct place to inject dependency. It has defined sequence of parameter like I shown below. You can't put dependency there.
link(scope, element, attrs, controller, transcludeFn) {
Inject $timeout
dependency in directive function
.
(function() { angular.module('github', []) .directive('mynav', function($window, $timeout) { //<-- dependency injected here return {
Then just use injected $timeout
inside link
function
$timeout(function() { console.log(element.width());})
setInterval(function(){ // code here $scope.$apply();}, 1000);
$apply is included as a reminder that since this is an external jQuery call you need to tell angular to update the DOM.
$timeout being an angular version automatically updates the DOM
Just replace timeout with setinterval like below:
(function() { angular.module('github', []) .directive('mynav', function($window) { return { restrict: 'A', link: function(scope, element, attrs, timeout) { scope.navItems = [{ "name": "home" }, { "name": "link1" }, { "name": "link2" }, { "name": "link3" }]; setInterval(function() { // replpace 'timeout' with 'setInterval' console.log($(element).width()); }) } } });})();
Hope it works for you.