Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
githop opened this issue Aug 14, 2017 · 0 comments

Comments

@githop
Copy link

githop commented Aug 14, 2017

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant