Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - Why we inject parameter inside array and function

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

app.controller('mycontroller', ['$scope', 'myFactory', 'Myothers', function ($scope, myFactory, Myothers) {}])

and see

app.controller('mycontroller', function ($scope, myFactory, Myothers) {})

Could you explain why we do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...