Search code examples
javascriptangularjsangularjs-directiveangularjs-serviceangularjs-controller

How to dynamically choose a repository/service to be used in a directive/controller?


I have a directive that gets data from the database but I want it to use different repositories (with the same API) in different places in the project. The incoming data has similar fields so that is not a problem. Is there a way to pass that as a parameter through the directive tag like

<div my-directive="my-directive" service="Services.MovieService"></div>
<div my-directive="my-directive" service="Services.ActorService"></div>

or what would be the best practice so I don't have if/else nightmares and dependency injection bloat using a string that would represent the service name?

How would that be done for plain controllers?

Thanks


Solution

  • A service can be dynamically injected into a controller of directive using the $injector by its name. Being able to inject services via controller arguments is just a convenience that Angular provides. Under the hood, the $injector is used by Angular to retrieve object instances. But we can use the $injector ourselves also.

    for instance, it is you controller function of your directive

      controller :($scope, $injector) {
      if(your_condition)
     { var ser= $injector.get(someService)  // someService contains the name of a service
      }
    

    here your condtion can be any condition in order to check whether to include a service or not