How to pass the directive of links $ q to angular?

I need to use the $q a link function of my directive. I need this to wrap a possible promise that is reconfigured with one of the arguments (see Example below). However, I do not know how to pass $q dependency on this function.

 angular.module('directives') .directive('myDirective', function() { return { scope: { onEvent: '&' } // ... link: function($scope, $element) { $scope.handleEvent() { $q.when($scope.onEvent()) { ... } } } } } 
+6
source share
3 answers

Just add it as a dependency on your directive, and $ q will be used as a link function. This is due to JavaScript closures .

The following 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()) { ... } } } } }]) 
+13
source

You cannot directly embed the communication function, but you can enter the factory function in the directive:

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

Or use array syntax for injection if you use minifier.

+2
source
 var module = angular.module('directives'); module.directive('myDirective', ['$q', function($q) { ... }]); 
+2
source

Source: https://habr.com/ru/post/977333/


All Articles