Skip to content

syntax error(s) in Typescript directive section for TodoAutoFocus as TS Class #165

@githop

Description

@githop

Hi Todd, I have used your guides / website in the past and they are awesome, keep up the good work!

I think I have found some errors in the TS version with regards to defining directives as TS Classes.
Below is the version currently published in your TS specific style guide.

export class TodoAutoFocus implements angular.IDirective {
  static $inject: string[] = ['$timeout'];
  restrict: string;

  constructor(private $timeout: angular.ITimeoutService) {
    this.restrict = 'A';
  }

  link($scope, $element: HTMLElement, $attrs) {
    $scope.$watch($attrs.todoAutofocus, (newValue, oldValue) => {
      if (!newValue) {
        return;
      }

      $timeout(() => $element[0].focus());
    });
  }
}

I believe there is one syntax error: $timeout is referenced in the link function without 'this'.
While not an error, in TS, instance properties can be set without assigning them in the constructor; e.g.

class MyDirective implements angular.Directive {
  restrict: string = 'A';
  priority: number = 0; 
}

If you aren't using ng-annotate, it doesn't seem to be enough to specify the required dependencies in a static $inject array (also 'ngInject' string literal is missing from the example). You may have to register them manually with a static method: e.g.

class MyDirective implements angular.Directive {
  static $inject = ['$timeout'];
  constructor($timeout: angular.ITimeoutService) {
  }
  static factory(): angular.IDirectiveFactory {
    const instance = ($timeout) => new MyDirective($timeout);
    instance.$inject = MyDirective.$inject;
    return instance;
  }
}
...

angular.module('foo' [])
.directive('myDirective', MyDirective.factory())

That seems to be working in my case (1.5.11, TS 2.4). I hope this could help other folks who have had similar issues.

Once again thanks again for all that you have contributed to the Angular(js) community!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions