2

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!

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

this is very interesting. I don't know why but I tend to be stingy with my modules.
Do you have a recommended project folder structure for getting more liberal with modules like this? I currently organize by type first (service, controller, etc) then by area, but this seems like it would benefit from module first.
You could take a look at how the angular-ui/ui-utils (github.com/angular-ui/ui-utils) project structures its modules. It allows a consumer to use a single utility or include the entire collection of modules.
I got Error: $injector:modulerr Module Error following the syntax in your answer with angularjs 1.5.8
You might want to go back and look at your module names. There is a chance that something was named incorrectly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.