【问题标题】:How to inject one controller function to another controller using angularjs?如何使用 angularjs 将一个控制器功能注入另一个控制器?
【发布时间】:2015-09-30 07:19:02
【问题描述】:

我有两个 ng 控制器,例如控制器 1、控制器 2,我想在控制器 1 中注入控制器 2 方法,并且我想通过我的 JS API 函数使用“document.querySelector('[ng-controller=custom-entity-design -ctrl]')"。 有可能得到吗?我尝试使用也不起作用的工厂服务。这是说错误 $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");
         };
  }]);

谁能帮我实现这个目标。

【问题讨论】:

  • 你不能将控制器注入到另一个控制器中,请查看服务。
  • 使用工厂或服务
  • @pixelbits 。我尝试使用工厂它不起作用。请看看我的小提琴jsfiddle.net/bagya1985/4o7rcj4y
  • 您必须使用服务,而不是工厂。服务,我们在需要在控制器之间共享数据的地方使用。工厂,我们在需要创建对象的不同实例的地方使用。

标签: javascript jquery angularjs


【解决方案1】:

使用.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() 服务时,请确保返回对象 {} 中的所有内容,使用此对象您可以提供多个值/方法等。

Check the plnkr.

【讨论】:

    猜你喜欢
    • 2014-10-14
    • 1970-01-01
    • 2011-08-30
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多