Why we inject parameter inside array and function

前端 未结 3 1572
梦谈多话
梦谈多话 2020-12-04 02:27

I\'m a beginner in Angular development. I don\'t know why we inject twice argument inside for controller like:

app.controller(\'mycontroller\', [\'$scope\',          


        
3条回答
  •  孤城傲影
    2020-12-04 03:19

    The reason is to protect the code from javascript minification.

    The $inject makes sure that the variable names are preserved in the form of strings.

    So ideally your app code should look something like this:

     var app = angular.module('YourApp', []);
     var appCtrl = app.controller('AppCtrl', AppCtrl);
    
     appCtrl.$inject = ['dep1', 'dep2']; //add all the dependencies
    
     function AppCtrl (dep1,dep2){  //add the name of the dependencies here too
        //your controller logic
     }
    

    During minification javascript replaces variable name with custom names, so dep1 might be replaced by d and hence will cause error.

    But $inject will let angular know that the actual name of the dependency is dep1 as it is stored in the form of string value which is protected from minification.

    Hence we use $inject.

提交回复
热议问题