将函数和数组作为AngularJS控制器传递有什么区别?

Ada*_*ean 5 angularjs angularjs-controller

这两个都有效,但每个实现之间的实际差异是什么?我确信每种方法背后都有合理的推理,我希望能够开悟.

angular.module('app').controller('GeneralCtrl', 
    function($scope, $location, exampleService) {
        $scope.variable = exampleService.getExampleVariable();
    }        
);

angular.module('app').controller('GeneralCtrl', 
    ['$scope', '$location', 'exampleService', function($scope, $location, exampleService) {
        $scope.variable = exampleService.getExampleVariable();
    }]
);
Run Code Online (Sandbox Code Playgroud)

这些之间的实际区别是什么?你会用不同的方式使用它们?为什么?

答:当minifiers重命名参数名称时,后者是minification安全的,因此无法从名称中推断出依赖关系,因此必须进行注释.

JJ *_*wax 4

这就是 Angular 所说的依赖注入的“内联表示法”(有关详细信息,请参阅http://docs.angularjs.org/guide/di )。

在您给出的示例中,该ng-controller指令实际上是在幕后进行工作,将$scope, $location, 和exampleService连接到您首先提供给该变量的变量中function。默认情况下,它根据变量名称执行此操作(即,它假设调用的变量$scope正在请求$scope依赖项)。

也就是说,当您缩小代码时,变量名称也会被缩短(即$scope可能变成a)。当这种情况发生时,Angular 现在不再知道变量的含义了。

一种选择是添加

GeneralCtl.$inject('$scope', '$location', 'exampleService')
Run Code Online (Sandbox Code Playgroud)

另一种方法是像第二个示例中那样提供这些字符串。这可以确保即使变量名称发生变化,您也可以告诉 Angular 它们应该代表什么,并且它知道如何正确设置它们。