我有一个这样定义的自定义指令:
app.directive('tagProfile', ['userService', function(userService) {
return {
restrict: 'E',
scope: {
mode: '@'
,entity: '='
,onUpdate: '&'
,onCancel: '&'
},
templateUrl: '/public/user/tag_profile.html',
controller: ['$scope', function($scope) {
$scope.userService = userService
}],
link: function(scope, element, attrs) {
}
}
}])
请注意,我注入(inject)了
userService
在 directive
,因为大多数关于自定义指令的教程都在那里注入(inject)了依赖项。我试图将它注入(inject) Controller 功能并且它也可以工作 controller: ['$scope', 'userService', function($scope, userService)
我最有可能只使用 Controller 功能,而不是链接功能。所以 userService 不会在链接中使用。除此之外,在这两个地方注入(inject)是一样的吗?或者哪个更好?
还有,为什么链接函数会注入(inject)
scope
而不是 $scope
?而且我们不使用显式注释来缩小支持?
最佳答案
I am most likely to use only controller function, not link function. so userService won't be used in link. Beside that, is injecting in both places the same? or which one is better?
如果您不打算使用链接步骤,请坚持注入(inject)
controller
.如果您想使用 Controller 和链接步骤,请在指令定义处进行注入(inject)。which of the two is better
没有区别或 which of the two is recommended
据我所知。这是指
userService
在这种情况下。注入(inject) $scope
进入指令定义,这不是我做过的事情,所以我不能说可能会带来什么样的副作用。是一样的吗?
Also, why is the link function injects scope instead of $scope? and we dont use explicit annotation for minify support?
link
的第一个参数将永远是 $scope
,所以不管你给它取什么名字。/**
* $compileProvider.$get
* L#6931 in angular.js
*/
return compile;
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
/**
* Redacted code...
*/
return function publicLinkFn(scope, cloneConnectFn, options) {
链接函数(由
compile
返回)不需要显式注释,因为它不容易(或,打开)DI。它的论点是预先设定的。这与在命名中明确一样有效:
return {
link: function (a,b,c) {
// { a: $scope, b: $element, c: $attrs }
}
}
tl;博士
directive
中注入(inject)“东西”如果您只在 controller
中使用“东西” . link
不向 DI 开放。 关于angularjs - 在哪里指定自定义指令依赖项。在 Controller 和指令级别是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31359440/