Adding angular dependencies in a link function shared by multiple directives
I have several directives that use the same link function. (The link function adds some extra state and html depending on the use case.) So I declared the following:
function common_linkfunc(){...}
var Directive_1 = function($scope, etc) {
return {restrict:"E", ...
link: common_linkfunc,
controller: function($scope, etc) {...}
};
}
Directive_1.$injects = ["$scope", "etc"];
angular.module("module").directive("D1", Directive_1)...;
The first change was when a link function is required $compile
. Then I need to add $templateCache
, and my question is, how can I do this systematically?
My first approach was to rewrite common_linkfunc
as
function foo($compile, $templateCache) {
return common_linkfunc($compile, $templateCache) {...}
}
and then use this in every directive:
... reference: foo ($ compile, $ templateCache), ...
But this is copy and paste! Is there an easier and less error prone way to do the same?
source to share
Whatever the solution, you need to pass some kind of argument to your generic link function, because Angular won't inject anything into it for you. That being said, I can think of two different approaches:
1) Use arguments
app.directive('foo', function($http, $timeout) {
return {
restrict: 'E',
link: linkFn1.apply(null, arguments)
}
});
function linkFn1($http, $timeout) {
return function(scope, element, attrs) {
// ...
};
}
The downside here is that the order of the arguments in the directive function matters. If any other directive uses a different order, the code will not work as expected.
2) Use $injector
app.directive('bar', function($injector) {
return {
restrict: 'E',
link: linkFn2($injector)
}
});
function linkFn2($injector) {
var $http = $injector.get('$http'),
$timeout = $injector.get('$timeout');
return function(scope, element, attrs) {
// ...
};
}
source to share