gpt4 book ai didi

angularjs - 将函数和数组作为 AngularJS Controller 传递有什么区别?

转载 作者:行者123 更新时间:2023-12-04 20:10:03 25 4
gpt4 key购买 nike

这两种方法都有效,但每种实现之间的实际区别是什么?我确信每种方法背后都有逻辑推理,我希望得到启发。

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();
}]
);

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

答:事实证明,后者是缩小安全的,因为缩小器重命名了参数名称,因此无法从它们的名称中推断出依赖关系,因此必须进行注释。

最佳答案

这就是 Angular 所称的依赖注入(inject)的“内联符号”(参见 http://docs.angularjs.org/guide/di 了解更多细节)。

在您给出的示例中,ng-controller指令实际上是在幕后工作,连接 $scope , $location , 和 exampleService进入您提供给第一个 function 的变量.默认情况下,它基于变量名称执行此操作(也就是说,它假定名为 $scope 的变量正在请求 $scope 依赖项)。

也就是说,当您缩小代码时,变量名称也会被削减(即 $scope 可能变为 a )。当这种情况发生时,Angular 现在不再知道你所说的变量是什么意思了。

一种选择是添加

GeneralCtl.$inject('$scope', '$location', 'exampleService')

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

关于angularjs - 将函数和数组作为 AngularJS Controller 传递有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com