Angularjs可以重复使用跨多个NG-应用服务 [英] Can Angularjs reuse a service across several ng-apps
问题描述
我试图创建将使用几个角度NG-应用的web应用程序,并且至少有两个可以使用相同的服务,code(他们不需要共享数据,但执行类似的功能),所以我怎样才能避免code重复?即,
myApp1.factories.factory('为MyService[功能(){
//东西,我不想重复
}])
...并在不同的页面上的不同分区中的其他应用程序:
myApp2.factories.factory('为MyService[功能(){
//东西,我不想重复
}])
有没有办法让两个应用程序重用服务code?或者是认为最佳实践来只有一个NG-应用程序为所有的HTML(即使在部分可能是独立的),只是使用控制器分东西了?
感谢
angular.module('myReuseableMod',[])。工厂('myReusableSrvc',函数(){
// code在这里
});VAR程序App1 = angular.module('myApp1',['myReuseableMod']);
App1.controller('someCtrlr',['$范围,myReusableSrvc',函数($范围,myReusableSrvc){
//控制器code
}]); //结束someCtrlrVAR App2的= angular.module('myApp2',['myReuseableMod']);
App2.controller('someCtrlr',['$范围,myReusableSrvc',函数($范围,myReusableSrvc){
//控制器code
}]); //结束someCtrlr
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
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
这篇关于Angularjs可以重复使用跨多个NG-应用服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!