2

I have an angular service (let's call it $superService), and I use it in lots of my directives, controllers etc. But I also have one specific directive that I would like to have the following behaviour: If I place any other directive inside that specific one, and that directives use $superService in their own controllers, I want another instance of $superService to be injected there. Let me give you an example of how I do it now:

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();
             }
         }
    };
}]);

So normally I would use oneDirective as follows:

<div one-directive></div>

But when i use it in specificDirective I have to write markup as this:

     <div specific-directive>
         <div one-directive custom-super-service="customSuperService"></div>
     </div>

Is there a better way to do this? Perhaps using custom service providers? I would want a solution in which i would write markup like this:

<div specific-directive>
    <div one-directive></div>
</div>

Without explicitly passing the custom instance to the directive.

kamilkp
  • 9,690
  • 6
  • 37
  • 56
  • Possible duplicate of [How to redefine a module in angularjs?](http://stackoverflow.com/questions/25742259/how-to-redefine-a-module-in-angularjs) – Paul Sweatte Jun 23 '16 at 18:39

1 Answers1

1

The dependency injection configuration is global, which means that if you modify the instance to be injected for a certain argument it will be changed in every context; things will break.

It's not quite clear to me what you're trying to accomplish in the end, but if you want some different behaviour based on the nesting context of your directives you can always influence that by having a parent controller that is required by a child directive.

Services are singletons in Angular, but you can always let a singleton maintain an object hash with different contexts.

See this plunker as example.

null
  • 7,906
  • 3
  • 36
  • 37