【发布时间】:2014-01-09 08:52:40
【问题描述】:
我有一个角度服务(我们称之为 $superService),我在很多指令、控制器等中使用它。但我也有一个特定的指令,我希望它具有以下行为:如果我放置任何该特定指令中的其他指令,并且该指令在自己的控制器中使用 $superService ,我希望将另一个 $superService 实例注入那里。让我举个例子说明我现在是如何做到的:
function SuperService(){
this.action = function(){
// some action
}
}
var module = angular.module('module');
module.service('$superService', SuperService);
module.directive('oneDirective', function(){
return {
scope: {
customSuperService: '='
},
// transulde, replace, restrict and other if needed
controller: ['$scope', '$superService', function($scope, $superService){
if($scope.attrs.customSuperService)
$superService = $scope.customSuperService;
// code utilizing $superService
}
link: function($scope, $element, $attrs){
$scope.attrs = $attrs;
}
};
}).directive('specificDirective', [function(){
return {
transclude: true,
replace: true,
scope: true,
template: '<div ng-transclude></div>',
compile: function(){
pre: function($scope, $element, $attrs, $transclude){
$scope.customSuperService = new SuperService();
}
}
};
}]);
所以通常我会按如下方式使用 oneDirective:
<div one-directive></div>
但是当我在 specificDirective 中使用它时,我必须这样编写标记:
<div specific-directive>
<div one-directive custom-super-service="customSuperService"></div>
</div>
有没有更好的方法来做到这一点?也许使用自定义服务提供商?我想要一个解决方案,我会像这样编写标记:
<div specific-directive> <div one-directive></div> </div>
没有显式地将自定义实例传递给指令。
【问题讨论】:
标签: javascript html angularjs dependency-injection