How to pass $q to angular directive link function?
Asked Answered
P

3

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()) {
            ...
         }
       }
     }
  }
}
Potassium answered 28/10, 2014 at 10:49 Comment(1)
You've got some pretty weird and probably broken syntax in that link function, by the way.Marcelline
R
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()) {
           ...
         }
       }
     }
  }
}])
Recitation answered 28/10, 2014 at 11:5 Comment(0)
M
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.

Marcelline answered 28/10, 2014 at 10:51 Comment(0)
K
2
var module = angular.module('directives');
module.directive('myDirective', ['$q', function($q) {
 ...
}]);
Kilohertz answered 28/10, 2014 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.