javascriptangularjsdependency-injectionangularjs-serviceangularjs-provider

How to inject services into a provider with angular 1.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.


Solution

  • 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 :)