Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use $timeout service in a Directive?

Basically, I want to measure the width of the element after angular has manipulated the DOM. So I would like to use $timeout for that, 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());
          })
        }

      }
    });
})();
like image 532
Artvader Avatar asked Aug 26 '16 10:08

Artvader


People also ask

What is the function of the $timeout service?

The '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.

How does $Timeout work in AngularJS?

setTimeout . The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service. The return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed. To cancel a timeout request, call $timeout.

What is the difference between $timeout and setTimeout?

Angular $timeout is a wrapper written for window. setTimeout in form of a try catch block which throws exceptions via $exceptionHandler service. $timeout accepts the function to be delayed, delay time, a boolean to invoke $. apply and parameters to be passed to the function.

Which service does angular use internally to process a page and handle directives on the page?

The $http service is one of the most common used services in AngularJS applications. The service makes a request to the server, and lets your application handle the response.


1 Answers

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());
})
like image 80
Pankaj Parkar Avatar answered Nov 15 '22 22:11

Pankaj Parkar