簡體   English   中英

如何從另一個模塊調用函數

[英]How to call a function from another module

在我的angularJS應用程序中,我有兩個模塊:模塊A和模塊B.

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

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

如何調用模塊B中的函數alertA

您需要在模塊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. 在模塊A中定義服務
  2. 將模塊A添加為模塊B的依賴項
  3. 將服務注入控制器

這是一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM