我不明白 $inject 在控制器中的使用 [英] I don't understand the use of $inject in controllers
问题描述
我对在 Angular 中注入完全感到困惑.我不知道在哪里使用它以及为什么.它是否仅用于工厂,如此处所述?
I am totally confused about inject in Angular. I do not know where to use it and why. Is it only used with factory as described here?
myController.$inject = ['$scope','notify'];
这里notify
是工厂的名字.
推荐答案
这是在您的代码缩小(如果您选择缩小)后支持依赖注入的一种方法.
That is one approach to support Dependency Injection after your code is minified (if you choose to minify).
当你声明一个控制器时,函数接受参数:
When you declare a controller, the function takes parameters:
function ($scope, notify)
当您缩小代码时,您的函数将如下所示:
When you minify the code, your function will look like this:
function (a, b)
由于 AngularJS 使用函数参数名称来推断 DI,您的代码将会中断,因为 AngularJS 不知道 a
或 b
.
Since AngularJS uses the function parameter names to infer DI, your code will break because AngularJS doesn't know about a
or b
.
为了解决这个问题,他们提供了额外的方法来声明控制器(或其他服务/工厂/等):
To solve this problem, they provided additional ways to declare controllers (or other services/factories/etc) for that matter:
对于控制器,使用
$inject
方法 - 在这里您传递一个映射到控制器函数参数的文字数组.所以,如果你提供
For controllers, use the
$inject
method - here you pass an array of literals that map to the parameters of your controller function. So, if you provide
['$scope', 'notify']
那么函数的第一个参数的值将是与此控制器关联的范围对象,第二个参数将是通知服务.
then the value of the first parameter to your function will be the a scope object associated with this controller and the second parameter will be the notify service.
在声明新的控制器、服务等时,您可以使用数组字面量语法.在这里,您可以执行以下操作:
When declaring new controllers, services, etc, you can use the array literal syntax. Here, you do something like this:
angular.module('myModule').controller('MyController', ['$scope', 'notify', function ($scope, notify) {
...
}]);
作为控制器函数参数的数组将 DI 对象映射到您的函数参数.
The array as a parameter to the controller function maps the DI objects to your function parameters.
在声明控制器等时,我更喜欢选项 #2,因为它更容易阅读/理解/交叉检查,因为它们都在同一个地方.
I prefer Option #2 when declaring controllers etc as it is easier to read/understand/cross-check since it is all in the same place.
这篇关于我不明白 $inject 在控制器中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!