我需要使用指令的$q
函数link
。我需要它来包装可能由参数之一重新调整的promise(请参见下面的示例)。但是,我不知道如何将$q
依赖项传递给此函数。
angular.module('directives')
.directive('myDirective', function() {
return {
scope: {
onEvent: '&'
}
// ...
link: function($scope, $element) {
$scope.handleEvent() {
$q.when($scope.onEvent()) {
...
}
}
}
}
}
最佳答案
只需将其添加为对您指令的依赖项,$ q就可以在链接函数中使用。这是因为JavaScript的closures。
以下是基于您的代码的示例。
angular.module('directives')
.directive('myDirective', ['$q', function($q) {
return {
scope: {
onEvent: '&'
}
// ...
link: function($scope, $element) {
$scope.handleEvent() {
$q.when($scope.onEvent()) {
...
}
}
}
}
}])