问题
I'm going through Angular JS Documentation. I'm not able to figure out one line that I mentioned in the below code. Can anyone explain ?
script.js:
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) { // This line
$scope.username = 'World';
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.username + '!';
};
}]);
index.html:
<div ng-controller="MyController">
Your name:
<input type="text" ng-model="username">
<button ng-click='sayHello()'>greet</button>
<hr>
{{greeting}}
</div>
I didn't understand this:
['$scope', function($scope) {}]
Here, why two $scope
s are used.
回答1:
Angular JS - Inline Array Annotation
Its used to avoid problems on minification. After minification the code looks like:
['$scope', function(a) {}]
So Angular knows which dependencies to inject.
Otherwise it would look like
function(a){}
after minification and angular did not know which dependency is meant.
You will find more information in the AngularJS Docs (Dependency Injection) https://docs.angularjs.org/guide/di
回答2:
With the help of Michael, I found this on Angular JS Docs.
Inline Array Annotation
This is the preferred way to annotate application components. This is how the examples in the documentation are written.
For example:
someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) { // ... }]);
Here we pass an array whose elements consist of a list of strings (the names of the dependencies) followed by the function itself.
When using this type of annotation, take care to keep the annotation array in sync with the parameters in the function declaration.
来源:https://stackoverflow.com/questions/45526580/inline-array-annotation-why-two-scopes-are-used-for-this-code