Javascript 如何从另一个模块调用函数
在我的angularJS应用程序中,我有两个模块:模块A和模块BJavascript 如何从另一个模块调用函数,javascript,angularjs,angularjs-scope,Javascript,Angularjs,Angularjs Scope,在我的angularJS应用程序中,我有两个模块:模块A和模块B angular.module('A').controller('ACtrl',function($scope){ $scope.alertA = function(){alert('a');} //... }); angular.module('B').controller('BCtrl',function($scope){ //... }); 如何调用模块B中的函数alertA?按照以下步骤重构代码:
angular.module('A').controller('ACtrl',function($scope){
$scope.alertA = function(){alert('a');}
//...
});
angular.module('B').controller('BCtrl',function($scope){
//...
});
如何调用模块B中的函数
alertA
?按照以下步骤重构代码:
angular.module('A').service('API', function ($http) {
this.getData = function () { return $http.get('/data'); };
});
angular.module('B', ['A']).controller('dashboardCtrl', function ($scope, API) {
API.getData().then(function (data) { $scope.data = data; });
});
您需要在模块a中定义工厂:
var moduleA= angular.module('A',[]);
moduleA.factory('factoryA', function() {
return {
alertA: function() {
alert('a');
}
};
});
angular.module('B',['A']).controller('BCtrl',function($scope,'factoryA'){
factoryA.alertA();
});
然后使用模块B中的警报A
工厂:
var moduleA= angular.module('A',[]);
moduleA.factory('factoryA', function() {
return {
alertA: function() {
alert('a');
}
};
});
angular.module('B',['A']).controller('BCtrl',function($scope,'factoryA'){
factoryA.alertA();
});
您的函数应该重构为服务。这就是函数在Angular中共享和交叉注入的方式。另外:很好,谢谢你的回答。你好!如果能解决您的问题,请接受我的回答。:)