Georgi Naumov
Georgi Naumov

Reputation: 4201

Uncertainty about the use of services in AngularJS

I have one question about using of services. I'm creating services in this way and everything working properly. Here is my code.

var appName = angular.module('appName', ['configuration', 'angularSpinner']);

// this is whay that I creating services. 
(function (module) {
    var moduleName = function () {
        return function(inputVar) {
                // some work with 
        // inputVal variable 
            return result;
        }
    };

    module.factory("moduleName", [moduleName]);
}(angular.module("appName")));


// in this way I'm using service into controller. 
appName.controller('controllerName', function($scope, moduleName) {

});

My question is do I need to set 'moduleName' in 'appName'. Ie like this:

var appName = angular.module('appName', ['configuration', 'angularSpinner', 'moduleName']);

In both cases everything works properly. I would appreciate any comments and recommendations.

Best regards.

Upvotes: 1

Views: 63

Answers (2)

Mark-Sullivan
Mark-Sullivan

Reputation: 186

My question is do I need to set 'moduleName' in 'appName'. Ie like this:

No you do not, unless you actually create another module. In this case your moduleName is actually your factory name. If you wanted to create another module you would do this.

var myModule = angular.module('myModule', []);

myModule.factory('myFactory', [function(){ /* factory definition */ }]);

var app = angular.module('app', ['myModule']);
// this will now make myFactory available to my app

Your using the factory method which returns a function. If you need a service (a singleton object) then use the service method.

I create my services like this

var app = angular.module('app', []);

app.service('myService', [function(){

    var serviceMember = { name: 'something' };

    var serviceMethod = function() { };

    // revealing module pattern
    return {
        serviceMember: serviceMember,
        serviceMethod: serviceMethod
    };

}]);

Upvotes: 1

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38663

Yes, You needed

var appName = angular.module('appName', ['configuration', 'angularSpinner', 'moduleName'])

The 'appName' is Main Module name, and the 'moduleName' is sub module name. If you put the 'moduleName' with 'appName', then you can call 'modulname' functions wherever you use the 'appName'.

Main Module :

angular.module('appName',

Sub Module :

, ['configuration', 'angularSpinner', 'moduleName']

The concepts works by Dependency Injection Concept

Upvotes: 1

Related Questions