Inline Array Annotation - Why two $scopes are used for this code [duplicate]

徘徊边缘 提交于 2019-12-18 09:19:13

问题


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 $scopes 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!