Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass $q to angular directive link function?

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()) {
            ...
         }
       }
     }
  }
}
like image 641
mrzasa Avatar asked Oct 28 '14 10:10

mrzasa


2 Answers

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()) {
           ...
         }
       }
     }
  }
}])
like image 123
Caleb Kiage Avatar answered Sep 28 '22 07:09

Caleb Kiage


var module = angular.module('directives');
module.directive('myDirective', ['$q', function($q) {
 ...
}]);
like image 20
Lokesh Avatar answered Sep 28 '22 06:09

Lokesh