Reputation: 275
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
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