angularjs - 为什么将 $scope 放在 Controller 上的依赖项数组中?

标签 angularjs

我见过很多人,包括 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/

相关文章:

javascript - 如何过滤显示的数组并重新显示过滤后的列表?

javascript - 在 AngularJS 中像撤消一样实现 Amazon Wishlist

javascript - 为什么指令在 $rootScope 中可用?

javascript - Angularjs 数据存储最佳实践

javascript - angular 的 Controller 方法如何使 $scope 可用于我的函数参数

javascript - 按特定顺序对对象进行排序 - Angular

javascript - AngularJS中单个路由器的多个 View

javascript - 循环中$index的值

javascript - 无法获取textAngular的模型值

javascript - 使用 Highcharts 和 AngularJs 的实时条形图