What does ngInject do in the following piece of co

2020-05-25 06:27发布

AngularJS controller code:

function AuthConfig($stateProvider, $httpProvider) {
  'ngInject';

  // Define the routes
  $stateProvider

  .state('app.login', {
    url: '/login',
    templateUrl: 'auth/auth.html',
    title: 'Sign in'
  })

  .state('app.register', {
    url: '/register',
    templateUrl: 'auth/auth.html',
    title: 'Sign up'
  });

};

export default AuthConfig;

I am not able to figure out what is the use of ngInject. Could someone please help me?

标签: angularjs
2条回答
虎瘦雄心在
2楼-- · 2020-05-25 06:51

Usually ngInject is needed for the application to work when minified once you deploy in production. If you remove it and use optimize version it should fail.

Read more about AngularJs Minification and Annotation

查看更多
一纸荒年 Trace。
3楼-- · 2020-05-25 06:56

'ngInject'; does nothing by itself, it's just a string literal. A tool called ng-annotate uses it as a flag : if a function starts with 'ngInject';, it will be processed by ng-annotate.

Basically, ng-annotate will transform

angular.module("MyMod").controller("MyCtrl", function($scope, $timeout) {
    "ngInject";
    ...
});

to

angular.module("MyMod").controller("MyCtrl", ["$scope", "$timeout", function($scope, $timeout) {
    "ngInject";
    ...
}]);

in order to make the code minification-safe.

If you're not using ng-annotate, you can safely ignore or remove the expression. Be careful though, you might break the build process of the project if it does use ng-annotate. For more information about ng-annotate and what it does, see https://github.com/olov/ng-annotate

查看更多
登录 后发表回答