【问题标题】:AngularJS override service injection in some casesAngularJS 在某些情况下会覆盖服务注入
【发布时间】: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:

&lt;div one-directive&gt;&lt;/div&gt;

但是当我在 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


【解决方案1】:

依赖注入配置是全局的,这意味着如果您修改要为某个参数注入的实例,它将在每个上下文中更改;事情会破裂。

我不太清楚你最终想要完成什么,但如果你想要基于指令的嵌套上下文的一些不同的行为,你总是可以通过拥有一个所需的父控制器来影响它子指令。

服务是 Angular 中的单例,但您始终可以让单例维护具有不同上下文的对象哈希。

See this plunker as example.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多