Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS. Passing Service as an argument to Directive

Tags:

angularjs

I have my own directive: <form-wrapper>

For now this directive uses its own internal controller that use some Service (User service)

Like this:

 directives.directive("formWrapper", ['User',  function(User) {
        return {
         ...        
         controller: function($scope, $location, User) {

                    $scope.fields = User.get( {id: "1"}  );              // GET
        ...

As you can see: I use hard-coded Service (User).

Question: How could I pass Service as an argument to the Directive? To use it like this:

  Service = comesFromArgument
  $scope.fields = Service.get( {id: "1"} )

I guess if I pass Service name as string (as service name) it will not help. And passing argument usually happens in link-function but not in the controller.

UPDATE (more explanation) :

When use directives.directive("formWrapper", ['User', function(User) { the name 'User' lead to inject User service, because this it the way how IoC work here I guess. It knows that this is a service. But if I did:

<form-wrapper service="User"> // this is what I want.

Then, "User" will be just a string, not reference to the User service.

like image 515
ses Avatar asked Nov 17 '13 16:11

ses


1 Answers

You can use angular's $injector service to inject a service given a string in your controller.

In the HTML:

<form-wrapper my-attr-with-service="User">
  ...
</form-wrapper>

In the directive definition:

controller: function ($scope, $element, $attrs, $injector) {
    var myService = $injector.get($attrs.myAttrWithService);
    // ...
}
like image 136
musically_ut Avatar answered Sep 29 '22 20:09

musically_ut