What Does /** @ngInject */ Do?
JimLynchCodes opened this issue · comments
Hi. Awesome generator. However, I don't think the docs clearly explain the /** @ngInject / doctag in the controller files. Is this importing css? Is it making so you don't have to write your dependencies twice? Do I need to put this at the top of every controller? What about services, factories, and directives? It looks like they all have this /* ngInject */, but when I delete it the app doesn't break so what are they doing? Just trying to make it clear because I'm writing a blog post about it.
thanks.
I've a projet in typescript and /* @ngInject */ is used as an annotation.
I'm using it only on controllers.
Example in modal class :
static $inject = ['$uibModalInstance', 'i18nService', 'uiGridConstants', 'title', 'type'];
constructor($uibModalInstance: ng.ui.bootstrap.IModalServiceInstance, $http: angular.IHttpService, i18nService: any, uiGridConstants: any, title: string, type: string) { ... }
Is the same as
/* @ngInject */
constructor($uibModalInstance: ng.ui.bootstrap.IModalServiceInstance, $http: angular.IHttpService, i18nService: any, uiGridConstants: any, title: string, type: string) { ... }
You can find more info here
These annotations are for https://github.com/olov/ng-annotate which resolves DI issues with minifying.
Ok. I am confused though because even when I delete the line /** @ngInject / everything still works fine. Do I NEED to have /* @ngInject */ there or is it optional?
It's needed for the application to work when minified. If you remove it and use optimize version (serve:dist) it should fail.
@Swiip it should still work if using "Controller.$inject" right?
So this would also work right?
( function() {
'use strict';
angular
.module( 'www' )
.component( 'foo', {
templateUrl: 'app/components/foo/foo.html',
controller: Controller
} );
Controller.$inject = [];
function Controller() {
}
} )();
Or do we need to have "/@ngInject/" as well?
( function() {
'use strict';
angular
.module( 'www' )
.component( 'foo', {
templateUrl: 'app/components/foo/foo.html',
controller: Controller
} );
Controller.$inject = [];
/* @ngInject */
function Controller() {
}
} )();
@mackelito it is redundant if your Controller.$inject = []; captures your dependencies, otherwise it's a good best practice to catch any missing dependencies on minification since it is harmless if not needed. To finish the original question, 'ngInject'; is not required for your code to work but it is required if you want to package and minify your code for production using (serve:dist) as @Swiip above mentioned.