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.
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);
    // ...
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With