如何从另一个模块调用函数

时间:2016-04-18 21:10:20

标签: 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

2 个答案:

答案 0 :(得分:7)

您需要在模块A

中定义工厂
var moduleA= angular.module('A',[]);
moduleA.factory('factoryA', function() {
    return {
        alertA: function() {
            alert('a');
        }    
    };
});

然后使用模块B 中的alertA工厂:

angular.module('B',['A']).controller('BCtrl',function($scope,'factoryA'){
    factoryA.alertA();
});

答案 1 :(得分:1)

按照以下步骤重构您的代码:

  1. 在模块A中定义服务
  2. 将模块A添加为模块B的依赖
  3. 将服务注入控制器
  4. 以下是一个例子:

    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; });
    });