Can Angularjs reuse a service across several ng-apps

All we need is an easy explanation of the problem, so here it is.

I am trying to create a web app that will use several angular ng-apps, and at least two can use the same service code (they DONT need to share the data, but they perform similar functions), so how can I avoid code duplication? That is,

myApp1.factories.factory( 'myservice' [ function(){
   // stuff I dont want to repeat
}])

…and on a different div on a different page elsewhere in the app:

myApp2.factories.factory( 'myservice' [ function(){
   // stuff I dont want to repeat
}])

Is there a way to get the two apps to reuse that service code? Or is it considered best practices to have only one ng-app for all your html (even when the parts might be independent), and just divide things up using controllers?

Thanks

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

angular.module('myReuseableMod', []).factory('myReusableSrvc', function() {
    // code here
});

var App1 = angular.module('myApp1', ['myReuseableMod']);
App1.controller('someCtrlr', ['$scope', 'myReusableSrvc', function($scope, myReusableSrvc) {
    // controller code
}]); // end someCtrlr

var App2 = angular.module('myApp2', ['myReuseableMod']);
App2.controller('someCtrlr', ['$scope', 'myReusableSrvc', function($scope, myReusableSrvc) {
    // controller code
}]); // end someCtrlr

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply