javascript 指令的链接函数的参数是否依赖于 DI?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15871129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Do the parameters of a directive's link function rely on DI?
提问by ejoubaud
In:
在:
module.directive 'name', ->
(scope, element, attr) ->
# Whatever implemenation
Do the scope
, element
and attrs
parameters of the link function rely on name-inferred Dependency-Injection? If yes, how can I make them minification proof ?
链接函数的scope
,element
和attrs
参数是否依赖于名称推断的依赖注入?如果是,我怎样才能使它们成为缩小证明?
Or do they rely on good old arguments order for what's passed into them ?
或者他们是否依靠良好的旧参数顺序来获取传递给他们的内容?
回答by Arun P Johny
No, the link function has a predefined set of parameters.
不,链接函数有一组预定义的参数。
function link($scope, $element, attrs, ctrl) {
//Your method
}
They are
他们是
- Scope of the element
- The element itself (jquery/mini jquery wrapped)
- Attribute set of the element
- Any controllers used in
required
- 元素的范围
- 元素本身(jquery/mini jquery 包装)
- 元素的属性集
- 使用的任何控制器
required
回答by z0r
If you want to use DI with a directive (as I did), put the arguments to be injected in the directive factory function instead of the link function:
如果您想将 DI 与指令一起使用(就像我所做的那样),请将要注入的参数放入指令工厂函数而不是链接函数中:
module.directive('name', function($timeout) {
return function(scope, element, attrs) {
...
};
});
To allow for minification, put the function argument in an array like you do for controllers:
为了允许缩小,把函数参数放在一个数组中,就像你对控制器所做的那样:
module.directive('name', ['$timeout', function($timeout) {
return function(scope, element, attrs) {
...
};
}]);
See the current timeexample in the docs.
请参阅文档中的当前时间示例。
Edit: See herefor a demo that injects the $timeout
service. You can do the same thing when returning a directive (e.g. return {restrict: 'E', link: function() {...}}
) object instead of a function.
编辑:有关注入$timeout
服务的演示,请参见此处。当返回一个指令(例如return {restrict: 'E', link: function() {...}}
)对象而不是一个函数时,你可以做同样的事情。