Javascript 如何使用angularjs将一个控制器函数注入另一个控制器?

Javascript 如何使用angularjs将一个控制器函数注入另一个控制器?,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,我有两个ng控制器,例如controller1、controller2,我想在controller1中插入controller2方法,我想使用“document.querySelector('[ng controller=custom entity design ctrl]')通过JS API函数进行访问。 有可能得到吗?我试着使用同样不起作用的工厂服务。它表示未定义错误$scope 源代码 **controller1** myApp.controller("controller1",fun

我有两个ng控制器,例如controller1、controller2,我想在controller1中插入controller2方法,我想使用“document.querySelector('[ng controller=custom entity design ctrl]')通过JS API函数进行访问。 有可能得到吗?我试着使用同样不起作用的工厂服务。它表示未定义错误$scope

源代码

**controller1**
  myApp.controller("controller1",function($scope, $document, $http, $localStorage) {
        $scope.test1 = function() {
              alert("test1");
         };
  });

  **controller2**
  myApp.controller("controller2",function($scope,$http,$compile,$localStorage, $log) {
        $scope.test2 = function() {
              alert("test2");
         };
  });
详细地说。。。我想从controller1访问$scope.test2方法

我试着使用工厂也不起作用

源代码:

  myApp.factory("testService", function($compile, $http, $scope) {     
   $scope.test2 = function() {
              alert("test2");
         };   
   }

   factory injected in controller1

   myApp.controller("controller1",['testService',function($scope, $document, $http, $localStorage) {
        $scope.test1 = function() {
              alert("test1");
         };
  }]);

有人能帮我做到这一点吗。

您使用
.factory()
的方法是正确的:

myApp.factory("testService", function($compile, $http, $scope) {     
   // just return the things in an object.
   return {
      name:"angular js",
      test2 : function(){ alert("test2") }
   }  
});

myApp.controller("controller1",['$scope', '$document', '$http', '$localStorage','testService', function($scope, $document, $http, $localStorage, testService) {
    $scope.test1 = function() {
        alert("test1");
        testService.test2(); // use the method from the testService.
    };
}]);
您在控制器的函数args中缺少服务,当您使用
.factory()
服务时,请确保返回对象
{}
中的所有内容,使用此对象可以提供多个值/方法等


您不能将控制器插入另一个控制器,请查看服务。请使用工厂或service@pixelbits . 我试过使用工厂,但它不起作用。请看一下我的小提琴,你必须使用服务,而不是工厂。服务,我们在需要在控制器之间共享数据的地方使用。工厂,我们在需要创建对象的不同-2实例的地方使用。