Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 271
Jan Avatar asked Dec 14 '25 02:12

Jan


1 Answers

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

like image 94
squiroid Avatar answered Dec 16 '25 19:12

squiroid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!