Callum Linington
Callum Linington

Reputation: 14417

Angular Module Loading

If I have this module:

angular.module('myMod', [])
.factory('MyService', ['$http', 'Common', function ($http, Common) {
    var neededUrl = Common.myUrl;
}]);

And I loaded up my app modules this way:

angular.module('myApp', [
    'myMod'
])
.factory('Common', function () {
    return {
        myUrl: "/Some/Url"
    }
});

Will myMod be able to pick up on the Common dependency and load it up?

Or is it better to do this:

angular.module('common.module', [])
.factory('Common', function () {
    return {
        myUrl: "/Some/Url"
    }
});

angular.module('myApp', [
    'common.module',
    'myMod'
])

Upvotes: 0

Views: 78

Answers (1)

Remco Haszing
Remco Haszing

Reputation: 7829

Both will work, but both are incorrect.

MyService from myMod depends on Common, not the other way around. Lets say you do choose to add Common to the module common.module. Then myMod should depend on common.module

angular.module('common.module', [])
.factory('Common', function () {
    return {
        myUrl: "/Some/Url"
    }
});


angular.module('myMod', [
    'common.module'
])
.factory('MyService', ['$http', 'Common', function ($http, Common) {
    var neededUrl = Common.myUrl;
}]);


angular.module('myApp', [
    'myMod'
]);

Using correct dependency management allows you to run isolated tests. The following is a jasmine example that should work:

describe('Test myMod', function() {

    beforeEach(module('myMod')); // from angular-mocks

    it('should work', function() {
        expect(true).toBeTruthy();
    })
});

If you picked either one of the options you suggested, the test case would fail, because MyService does depend on Common from common.module.

Upvotes: 2

Related Questions