2015-05-01 27 views
3

我有几个使用相同链接函数的指令。 (链接功能取决于使用情况增加了一些额外的状态和HTML)。所以我宣布这个如下:当链接功能需要$compile在跨多个指令共享的链接函数中添加角度依赖

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)...; 

第一个变化是。接下来,我需要添加$templateCache,我的问题是我怎样才能系统地做到这一点?

我的第一种方法是重写common_linkfunc作为

function foo($compile, $templateCache) { 
    return common_linkfunc($compile, $templateCache) {...} 
} 

,然后在每一个指令的使用:

... 链接:FOO($编译,$ templateCache), ...

但这是复制粘贴!有没有更容易和更容易出错的方法来做同样的事情?

回答

2

无论解决方案如何,您都需要将一些参数传递给您的常用链接函数,因为Angular不会为您注入任何内容。话虽这么说,我能想到的两种不同的方法:

1)使用arguments

app.directive('foo', function($http, $timeout) { 
    return { 
    restrict: 'E', 
    link: linkFn1.apply(null, arguments) 
    } 
}); 

function linkFn1($http, $timeout) { 
    return function(scope, element, attrs) { 
    // ... 
    }; 
} 

这里的缺点是,在指导作用事项参数的顺序。如果其他指令使用不同的顺序,代码将无法正常工作。

2)使用$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) { 
    // ... 
    }; 
} 

Working Plunker

+0

感谢 - 只是学到新的东西!我认为'$注射器'更灵活,更容易适应不断变化的需求。 – Dinesh