How to call a function from another module

家住魔仙堡 提交于 2019-12-18 09:11:40

问题


In my angularJS application, I have two modules : module A and module B.

angular.module('A').controller('ACtrl',function($scope){
    $scope.alertA = function(){alert('a');}
    //...
});

angular.module('B').controller('BCtrl',function($scope){
    //...
});

How to call the function alertA in the module B ?


回答1:


You need to define a factory in module A:

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

Then use the alertA factory in module B:

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



回答2:


Refactor your code in following these steps:

  1. Define a service in module A
  2. Add module A as dependency to module B
  3. Inject the service into the controller

Here is an example:

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


来源:https://stackoverflow.com/questions/36704347/how-to-call-a-function-from-another-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!