AngularJs - 注入 $scope

AngularJs - injecting $scope

下面两个例子是等价的吗?

1.

app.controller('ctrl',function($scope){});

2.

app.controller('ctrl',['$scope',function($scope){});

我是 AngularJs 的新手。从我的测试来看,他们做同样的事情,但不确定为什么会有两种不同的方式。

它们的功能相同,但通常首选第二种方法。这与缩小有关,而且当您分发应用程序时,如果变量名称不是数组中的项目,则可能会更改它们。

当然,如果您的控制器名称在缩小过程中发生变化,这将导致 Angular 的依赖项注入失败。

它们是等效的,并且可以正常工作。您可以选择一个而不是另一个,具体取决于您计划对项目执行的操作。使用第二种表示法对于缩小非常重要,它被称为 Inline Array Annotation 或更普遍的 Dependency Annotation.

您可以在 AngularJS 文档 here 中找到有关依赖项注入的详细信息。

Dependency Injection 是 angular js 的一大特色,用在 JS 缩小时,

JS 缩小之前:ctrl.js

app.controller('ctrl'['$scope','$rootScope','$state',function($scope,$rootScope,$state){
    $scope.message="Hello World"; //Must be maintain serial of Dependency Injection either wise show error

       });

JS 缩小后:ctrl.min.js

app.controller('ctrl'['$scope','$rootScope','$state',function(a,b,c){
a.message="Hello World";
    //So do not write $scope again just define 'a' instead of '$scope' like as $rootScope=b,$state=c ,so huge memory save in JS file.

   });