Hongbin Wang
Hongbin Wang

Reputation: 1186

How to call a function from another module

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 ?

Upvotes: 2

Views: 13957

Answers (2)

GG.
GG.

Reputation: 21864

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

Upvotes: 1

user6186801
user6186801

Reputation:

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

Upvotes: 7

Related Questions