6

I need to use $q a link function of my directive. I need it to wrap possible promise that is retuned by one of arguments (see the example below). I don't know however, how to pass $q dependency to a this function.

angular.module('directives')
 .directive('myDirective', function() {
   return {
     scope: {
       onEvent: '&'
     }
     // ...
     link: function($scope, $element) {
       $scope.handleEvent() {
         $q.when($scope.onEvent()) {
            ...
         }
       }
     }
  }
}
mrzasa
  • 22,895
  • 11
  • 56
  • 94

3 Answers3

14

Just add it as a dependency on your directive and the $q will be usable in the link function. This is because of JavaScript's closures.

Below is an example based on your code.

angular.module('directives')
.directive('myDirective', ['$q', function($q) {
   return {
     scope: {
       onEvent: '&'
     }
     // ...
     link: function($scope, $element) {
       $scope.handleEvent() {
         $q.when($scope.onEvent()) {
           ...
         }
       }
     }
  }
}])
Caleb Kiage
  • 1,422
  • 12
  • 17
2

You can't inject into the link function directly, but you can inject into the directive's factory function:

angular.module('directives')
 .directive('myDirective', function($q) {
   ...

Or use the array syntax for injection if you use a minifier.

Thomas
  • 174,939
  • 50
  • 355
  • 478
2
var module = angular.module('directives');
module.directive('myDirective', ['$q', function($q) {
 ...
}]);
Lokesh
  • 557
  • 4
  • 13