olov / ng-annotate

Add, remove and rebuild AngularJS dependency injection annotations
MIT License
2.03k stars 150 forks source link

Improve documentation for TypeScript support #180

Closed szahn closed 8 years ago

szahn commented 9 years ago

In TypeScript, to do dependency injection, we must statically include the $inject variable into each class. It would be great if ng-annotation would automatically recognize all TypeScript classes that are acting as Angular components and then inject the static $inject variable beside the constructor.

BEFORE INJECTION:

class MyDirective { 
constructor($scope:any,service:MyService)
      {

      }
 }

AFTER INJECTION:

class MyDirective { 
 static $inject = ["$scope","MyService"]; 
 constructor($scope:any,service:MyService)
      {

      }
 }
szahn commented 9 years ago

I see that the readme states that TypeScript is supported, however a sub-heading with sample code on annotating a constructor would have been useful.

szahn commented 9 years ago

The following code actually works without requiring an injection comments:

module MyModules {    
export class MyDirective implements ng.IDirective {
template: string;
scope : {
}
constructor(templateCache : ng.ITemplateCacheService) {
    this.template = templateCache.get("myTemplate.html");
}

}

}

(function() {
'use strict';
angular.module("MyModules").directive("myDirective", ($templateCache) => {
    return new MyModules.MyDirective($templateCache);
});
})()
Crotery commented 9 years ago

what about this code? it does not work, event if I add 'ngInject'; to class constructor()

angular.module("MyModules").directive("myDirective",MyDirective)
vitorreis commented 9 years ago

The dist version of my app does work if I omit the comment ngInject, but the development version works fine.

module myApp {

    export class RouterConfig {

        /** @ngInject */
        constructor($stateProvider: ng.ui.IStateProvider, $urlRouterProvider: ng.ui.IUrlRouterProvider) {
            $stateProvider
                .state('home', {
                  url: '/',
                  templateUrl: 'app/main/template/main.html',
                  controller: 'MainController',
                  controllerAs: 'main'
                }
            );

            $urlRouterProvider.otherwise('/');
        }

    }
}

This should work fine even with no ngInject annotation, right?

olov commented 8 years ago

The README is now very clear that it is preferred to use "ngInject"; with TypeScript. Closing