【问题标题】:How to call a function in another controller in angularjs如何在angularjs中调用另一个控制器中的函数
【发布时间】:2015-07-09 13:24:19
【问题描述】:
unified.controller('YourteamController', function uniYourteamController($scope) {    
    testController.listTeams();
});    

unified.controller('testController', function testController($scope) {
    $scope.listTeams = function() {
        //Listing process
    };    
});

我有两个控制器。我需要在另一个控制器(testController)中调用一个函数(listTeams())。如何使用 angularjs 调用它

【问题讨论】:

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

走服务之路。更容易测试,更符合“最佳实践”。

angular.module('sharedService', function () {
  function listTeams () {
    return 'teams!';
  }

  angular.extend(this, {
    listTeams: listTeams
  })
});

angular.module('ctrl1', function ($scope, sharedService) {
  angular.extend($scope, {
    listTeams: sharedService.listTeams
  });
});

angular.module('ctrl2', function ($scope, sharedService) {
  angular.extend($scope, {
    listTeams: sharedService.listTeams
  });
});

【讨论】:

    【解决方案2】:

    您需要将第一个控制器作为依赖注入到第二个控制器。 Here 是怎么做的。

    【讨论】:

    • 你的回答和我的评论有什么不同?
    【解决方案3】:

    执行以下操作...

      unified.controller('YourteamController', function uniYourteamController($scope) {    
            var testController= $scope.$new();
            $controller('testController',{$scope : testCtrl1ViewModel });
            testController.listTeams();
        });    
    
        unified.controller('testController', function($scope) {
            $scope.listTeams = function() {
                //Listing process
            };    
        });
    

    【讨论】:

      【解决方案4】:

      您必须创建一个服务,该服务将返回一个可在具有不同范围的两个控制器中使用的函数。

      =========================================

      unified.controller('YourteamController', function uniYourteamController($scope, $abc) {
      
      $abc.listTeams();
      });
      
      unified.controller('testController', function testController($scope, $abc) {
      $abc.listTeams();
      });
      
      unified.service('abc', function () {
      
      
      this.listitems = function () {
      
      }
      });
      

      【讨论】:

        【解决方案5】:

        试试这个

        unified.controller('YourteamController', function uniYourteamController($scope) {    
            $scope.$parent.listTeams();
        }); 
        

        【讨论】:

          猜你喜欢
          • 2014-12-11
          • 1970-01-01
          • 2015-02-06
          • 2015-06-10
          • 1970-01-01
          • 1970-01-01
          • 2015-09-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多