How to use the $ timeout service in a directive?

Basically, I want to measure the width of an element after angular has processed the DOM. So I would like to use $ timeout for this, but it keeps getting me errors.

HTML

<div ng-app="github"> <ul mynav> <li ng-repeat="nav in navItems">{{nav.name}}</li> </ul> </div> </div> 

CSS

 ul,li { display:inline-block; } li { margin-right:1em; } 

Js

 (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" }]; timeout(function() { console.log($(element).width()); }) } } }); })(); 
+5
source share
3 answers

link Function is not a suitable place for injecting addiction. He defined a sequence of parameters as shown below. You cannot install dependency there.

 link(scope, element, attrs, controller, transcludeFn) { 

Attachment $timeout dependencies in function directive.

 (function() { angular.module('github', []) .directive('mynav', function($window, $timeout) { //<-- dependency injected here return { 

Then just use the entered $timeout inside the link function

 $timeout(function() { console.log(element.width()); }) 
+4
source
 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 about the DOM update.

$ timeout, which is a version of angular, automatically updates the DOM

0
source

Just replace the timeout with setinterval, as shown 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 this works for you.

-1
source

All Articles