javascript - 为什么 angularjs Controller 声明具有这种语法结构?

标签 javascript angularjs dependency-injection

我一直看到以下 angularjs Controller 语法结构。

angular.module('7minWorkout').controller('WorkoutController', 
['$scope', '$interval', '$location', 
function ($scope, $interval, $location)
{
}]);

为什么参数名称重复?为什么不就这样

angular.module('7minWorkout').controller('WorkoutController', 
    ['$scope', '$interval', '$location', 
    function ()
    {
    }]);

   angular.module('7minWorkout').controller('WorkoutController', 
    [ 
    function ($scope, $interval, $location)
    {
    }]);

最佳答案

数组语法将帮助您缩小/丑化您的 js 代码。

angular.module('7minWorkout').controller('WorkoutController', 
  function ($scope, $interval, $location) {
    // code here
});

将被缩小和分解为:

angular.module('7minWorkout').controller('WorkoutController', 
 function (a, b, c) {
    // code here
});

因此 Angular 无法确定要注入(inject)哪些依赖项

另一方面,使用 array 声明:

angular.module('7minWorkout').controller('WorkoutController', 
 ['$scope', '$interval', '$location', function ($scope, $interval, $location) {
    // code here
}]);

将缩小为:

angular.module('7minWorkout').controller('WorkoutController', 
  ['$scope', '$interval', '$location', function (a, b, c) {
    // code here
}]);

因此 Angular 会知道 abc 代表什么。


如果您使用如下第一个示例代码,还有另一种注入(inject)变量的方法:

WorkoutController.$inject = ['$scope', '$interval', '$location'];

angular.module('7minWorkout').controller('WorkoutController', /* @ngInject */
  function ($scope, $interval, $location) {
   // code here
});

这将在代码被注释时创建上面提到的 $inject 方法。


所以,主要有四种annotation :

  1. > Implicit Annotation - 第一个示例代码
  2. > Inline Array Annotation - 第二个示例代码
  3. > $inject Property Annotation - $注入(inject)方法
  4. $ngInject 注释注解 - @ngInject方法

ng-注释

类似 ng-annotate 的工具让您在应用程序中使用隐式依赖注释,并在缩小之前自动添加内联数组注释。如果您决定采用这种方法,您可能需要使用 ng-strict-di

有关详细信息,请参阅 AngularJS Developer Guide - Using Strict Dependency Injection .

关于javascript - 为什么 angularjs Controller 声明具有这种语法结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31852967/

相关文章:

javascript - 改变标签底座 D3 的位置

javascript - 删除行脚本删除内容但不删除行

javascript - Laravel 5.0 : Calculation using LaravelCollective and jQuery

javascript - 如何用不同的设备模式强制元素的高度?

javascript - 扩展 angular.js 以自动将后缀附加到所有 templateURL 值

java - 集成测试每个测试具有不同属性值的 spring 配置

javascript - 我应该使用一个空的属性键吗?

angularjs - 指令 Controller 内的 Angular 集脏形式

php - Sonata 管理 Controller + 依赖注入(inject)

java - Spring - 如何将一个 bean 注入(inject)到在运行时多次创建的类中?