doug31415
doug31415

Reputation: 275

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

Upvotes: 15

Views: 6728

Answers (1)

m.e.conroy
m.e.conroy

Reputation: 3538

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

Upvotes: 27

Related Questions