Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Angularjs reuse a service across several ng-apps

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

like image 236
doug31415 Avatar asked Nov 07 '13 16:11

doug31415


1 Answers

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
like image 144
m.e.conroy Avatar answered Sep 28 '22 09:09

m.e.conroy