有没有办法从不同的页面调用一个AngularJS代码(函数)?我找到了2种方法,但它们并没有解决问题。
第一种方法是使用$rootScope
。然后我的函数逻辑将放入$rootScope
。
var sharedFunctions=angular.module('shared',['$rootScope']);
sharedFunctions.run(
function($rootScope){
$rootScope.translate=function(language, text){
for (var i = 0; i < text.translatedTexts.length; i++) {
if (text.translatedTexts[i].language == language) {
return text.translatedTexts[i];
}
}
};
}
);
但是我仍然需要在我的控制器中创建一个函数,调用$rootScope
函数。
$scope.translate=function(language,text){
$rootScope.translate(language,text);
}
第二种方式与第一种方式相似,但差异是我的函数的逻辑部分将放在service
或factory
中。
原因,为什么我不会采取这些解决方案:我必须在每个控制器中编写代码(只需几行,即调用主逻辑)。
答案 0 :(得分:0)
最后,我发现了如何在视图之间共享代码。
步骤1:创建根模块并配置基本功能。
'use strict';
var app=angular.module('rootApp',['ngRoute','appFactories']);
app.run(function($rootScope) {
$rootScope.translate = function (language, text) {}
//other functions
});
app.filter('filterName', function() {
.....
});
//other filters
步骤2:为我的视图创建子模块,并将根模块添加为依赖
'use strict';
var cardEditApp=angular.module('submoduleApp',['ngFileUpload','rootApp']);
第3步:在我的视图中使用ng-module="submoduleApp"
和我的子模块的名称。然后我可以使用我的子模块的控制器功能和根模块的功能。