使用$在控制器角度JS注入? [英] use of $inject in angular js in controllers?
问题描述
我是新来angularjs,我完全糊涂了约注射。我不知道在哪里使用它,为什么?与工厂这只用作此链接注入链接?
I am new to angularjs , I am totally confused about inject. I do not know where to use it and why? Is this only use with factory as explain in this link inject link?
myController.$inject = ['$scope','notify'];
的这里,通知是工厂的名称。的
推荐答案
这是支持你的code后,依赖注入一种方法是缩小的(如果你选择来缩小)。
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)
当你再缩小code,你的功能如下所示:
When you minify the code, your function will look like this:
function (a, b)
由于AngularJS使用函数参数的名称来推断DI,你的code将打破,因为AngularJS不知道 A
或 B
。
要解决这个问题,他们提供了更多的途径来声明为此事控制器(或其他服务/工厂/等):
To solve this problem, they provided additional ways to declare controllers (or other services/factories/etc) for that matter:
1)控制器,使用 $注
法 - 在这里你传递映射到控制器函数的参数文字的数组。所以,如果你提供
1) 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.
2)在申报新的控制器,服务等,可以使用数组文本语法。在这里,你做这样的事情:
2) 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.
我preFER选项#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.
这篇关于使用$在控制器角度JS注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!