3

In every piece of information I can find (including the angular documentation), the way to inject a service into a provider is through the $get method:

var myApp = angular.module('myApp', []);

myApp.provider('helloWorld', function() {
    this.$get = function() {
        return {
            sayHello: function() {
                return "Hello, World!"
            }
        }
    };
});

function MyCtrl($scope, helloWorld) {    
    $scope.hellos = [helloWorld.sayHello()];
}

This would work perfectly in angular 1.2 and below: http://jsfiddle.net/1kjL3w13/

Switch to angular 1.3 though, and the $get function completely breaks. It seems that whatever's returned from the $get function is no longer used to instantiate the provider, and thus is now useless for injecting f.e. services.

Same example as above, but using angular 1.3: http://jsfiddle.net/duefnz47/

This is exactly the behavior provided in the angular documentation. So either the documentation is wrong or I've completely misunderstood it. I don't really care if the $get method works as before or not though, I just need to be able to inject services reliably into my provider.

Jan
  • 5,688
  • 3
  • 27
  • 44
  • check my answer hope it help you :). – squiroid Jun 30 '15 at 12:06
  • Services, factory, constants, values, etc are not supposed to be injected into providers...rather they are done so on the factory that the provider exposes... – deostroll Jun 30 '15 at 12:20
  • @deostroll this is for building providers with different purposes but that can share methods and content between then. Think one "shared" provider with base functions that gets injected into many other providers. Does your statement still hold in that scenario? Also, the service that needs to be injected is f.e. the $window service, because I do need access to that inside my provider. And it does need to be a provider to be injectable in the `config` method. – Jan Jun 30 '15 at 13:59
  • This can be done with `angular.injector()`. but not sure about 1.3 support... – deostroll Jun 30 '15 at 14:24
  • Would it be mockable if I use `injector` straight up in my provider? – Jan Jun 30 '15 at 14:27

1 Answers1

2

Problem is you are using global controller which is not valid according to angular 1.3

So use

angular.module('myApp').controller('MyCtrl',function ($scope, helloWorld) {    
    $scope.hellos = [helloWorld.sayHello()];
});

Here is updated fiddle

**

Migration Document official

** Hope it help :)

squiroid
  • 13,809
  • 6
  • 47
  • 67
  • 1
    Thanks, this solved this issue, sadly it was an abstraction that's probably a bit too abstracted to really be indicative of my actual problem. With so many levels of complexity it's hard to come up with a simple example that exhibits the behavior. I'm still having the issue in my actual code which does not use a global controller. I'll set it as answered since you did solve this particular issue though. – Jan Jun 30 '15 at 14:03