我见过很多人,包括 Angular 文档,都这样声明 Controller :
app.controller('ExampleController', [$scope, $http, function($scope, $http) {
$scope.name = "Bob";
}]);
为什么我们需要将 $scope 放入依赖数组中?这是旧版本 Angular 的语法吗?我们可以这样写吗:
app.controller('ExampleController', [$http, function($scope, $http) {
$scope.name = "Bob";
}]);
两者有区别吗?谢谢。
最佳答案
您所看到的实际上是这样的:
app.controller('ExampleController', ["$scope", "$http", function($scope, $http) {
$scope.name = "Bob";
}]);
这样做的原因是为了处理缩小问题。当缩小 $scope 时,$http 将被压缩为 a 和 b 等变量,因为依赖注入(inject)无法通过缩小来工作。 Angulars 对此的解决方案是使 Controller 成为一个可以在其中传递字符串的数组。
参见:https://docs.angularjs.org/tutorial/step_05#-prefix-naming-convention
关于angularjs - 为什么将 $scope 放在 Controller 上的依赖项数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24000266/