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

Hon*_*ang 2 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){
    //...
});
Run Code Online (Sandbox Code Playgroud)

如何调用alertA模块B中的函数?

小智 7

您需要在模块A中定义工厂:

var moduleA= angular.module('A',[]);
moduleA.factory('factoryA', function() {
    return {
        alertA: function() {
            alert('a');
        }    
    };
});
Run Code Online (Sandbox Code Playgroud)

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

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