Travis Watson
Travis Watson

Reputation: 1749

AngularJS: Provider after Module.config?

If I want to create a custom provider and configure it within Module.config, Angular appears to require the provider be declared first.

This does not work:

module.config(function(myServiceProvider) {  });
module.provider('myService', function() {  });

This does work:

module.provider('myService', function() {  });
module.config(function(myServiceProvider) {  });

Only the order is different.

I've tried this with Module.run as well, and it seems to have the same limitation. Is there any way around this other than ensuring the config code is loaded after the provider code?

Edit: Here's a JSFiddle of the working order, and a JSFiddle of the NON-working order. Note the only thing that changes is the order!

Upvotes: 2

Views: 900

Answers (1)

Brian Lewis
Brian Lewis

Reputation: 5729

You might want to consider creating separate modules. This will not only allow give you the flexibility you are looking for, it will help to make your code easier to test and maintain.

angular.module('myModule', ['myModule.controllers', 'myModule.services']).config(function (myServiceProvider) {
    myServiceProvider.setName('Sam');
});
angular.module('myModule.controllers', []).controller('myController', function ($scope, myService) {
    $scope.name = myService.getName();
});
angular.module('myModule.services', []).provider('myService', function () {
    var name = 'John';
    this.setName = function (newName) {
        name = newName;
    };
    this.$get = function () {
        return {
            getName: function () {
                return name;
            }
        };
    };
});

Here is an updated jsfiddle.

Upvotes: 2

Related Questions