【问题标题】:Angularjs call a function from a controller to another controllerAngularjs从一个控制器调用一个函数到另一个控制器
【发布时间】:2017-12-14 10:54:36
【问题描述】:

几个小时以来,我一直在尝试从一个控制器调用一个函数到另一个控制器。

我看到了类似的主题(我试过但我肯定太糟糕了): What's the correct way to communicate between controllers in AngularJS? Can one controller call another?

但没有像我正在寻找的具体例子。

控制器:

app.controller('Controller1', function($scope, $modal, $modalInstance, job, JobServices) {

   $scope.job1 = function () {
       JobServices.job1($scope.name)
       .success(function(data, status, headers, config) {
          // something
       });
   }


   function doSomething(){
      // How call test() from controller2 ?
   }
}

app.controller('Controller2', function($scope){
   function test(){
      do a lot of things
   }
}

最好和最简单的方法是什么?

非常感谢

编辑:

我已经尝试过使用类似的东西:

app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope, $modal, $modalInstance, job, JobServices) {

但我有错误说 job1 未定义...

【问题讨论】:

  • 您可能希望将您的逻辑放入 service/factory 并在其上调用函数。
  • 我的问题是我在使用 function($scope, $modal, $modalInstance, job, JobServices) 到 ['$scope', '$rootscope', function($ scope, $rootscope, $modal, $modalInstance, job, JobServices) 来自我的函数,比如 job1(见我的编辑)

标签: angularjs controller


【解决方案1】:

你可以使用 $scope.$emit 和 $scope.$on,有点像这样

app.controller('Controller1', ['$scope', '$rootScope' function($scope) {
   function doSomething(){
       $rootScope.$emit("callController2", {});
   }
}

app.controller('Controller2', ['$scope', '$rootScope' function($scope) {
  $rootScope.$on("callController2", function(){
    this.test();
  });
  function test(){
    do a lot of things
        }
}

【讨论】:

  • 正如我所说的那样,我已经尝试过了,但使用 ['$scope', '$rootScope'... 时出现错误(说它未定义)...(请参阅我的编辑)
猜你喜欢
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 2015-09-07
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多