AngularJS access service from different module

after made some changes html should look like:

<body ng-app="myModule" ng-controller="appservices"></body>

Above section of code used to bootstrap your angular module

angular should look like:

 var myModule = angular.module('myModule', ['module1','module2']);
    myModule.controller("appservices",["$scope","mod1factory","mod2factory",function($scope,mod1factory,mod2factory){

       console.log(mod1factory.getData()) ;
       console.log(mod2factory.getData()) ;
    }]);
    var mod1 = angular.module('module1',[]);
    mod1.factory("mod1factory",function(){
        var mod1result = {};
        mod1result = {
            getData: function(){
                return "calling module 1 result";
            }
        }
        return mod1result;
    });
    var mod2 = angular.module('module2',[]);
    mod2.factory("mod2factory",function(){
        var mod2result = {};
        mod2result = {
            getData: function(){
                return "calling module 2 result";
            }
        }
        return mod2result;
    });

Explanation: created a main module myModule and inject other modules(in my case module1 and module2) as dependency so by this you can access both the module inside the main module and share the data between them

console.log(mod1factory.getData()) ;
console.log(mod2factory.getData()) ;

created two factory and inject it in my controller mod1factory and mod12factory in my case . so mod1 & mod2 are both differnt modules but can share info. inside main controller myModule


A Module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. Modules can list other modules as their dependencies. Depending on a module implies that required module needs to be loaded before the requiring module is loaded.

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

When you injected your module, the services got registered during the configuration phase and you could access them, so to make a long story short, it's the correct behavior and the core fundamentals of dependency injection in Angular. For example

angular.module('module1').service('appservice', function(appservice) {
   var serviceCall = $http.post('api/getUser()',"Role");
});

So how it can be accessed using angular.module('myModule');

angular.module('myModule').controller('appservice', function(appservice)
{
    var Servicedata= appservice.ServiceCall('role');
}

This how it can be accessed. If anyone has another suggestion please say so.

Tags:

Angularjs