AngularJS: 在同一模块的另一个控制器中注入控制器

AngularJS: Inject controller inside another controller from the same module

是否可以将控制器注入属于同一模块的另一个控制器?

示例:

var app = angular.module('myAppModule', [])
.controller('controllerOne', ['$scope', function($scope){
  $scope.helloWorld = function(){
    return 'Hello World';
  }
}])
.controller('controllerTwo', ['$scope', 'controllerOne', function($scope, controllerOne){
  console.log(controllerOne.helloWorld());
}])

我一直在 controllerOne 上收到未知的提供商。我不明白这怎么可能,因为它们共存于同一个模块中。任何帮助将不胜感激。

将您的逻辑移至 "service"(factory/service/provider)。我个人更喜欢工厂,我只是喜欢控制我自己的对象,而不是使用 this 或类似的其他选项。

使用服务,您可以让自己从控制器中抽象出 业务逻辑,并使该逻辑 -- 可重用 -- !

var app = angular.module('myAppModule', [])

// typically people use the word Service at the end of the name 
// even if it's a factory (it's all the same thing really...

.factory('sharedService', function () {

    var methods = {};

    methods.helloWorld = function () {
        return 'Hello World!';
    };

    // whatever methods/properties you have within this methods object
    // will be available to be called anywhere sharedService is injected.

    return methods;
})

Notice sharedService is injected

.controller('ControllerOne', ['$scope', 'sharedService', function($scope, sharedService) {
    $scope.helloWorld = sharedService.helloWorld();
}])

// Notice sharedService is injected here as well
.controller('ControllerTwo', ['$scope', 'sharedService', function($scope, sharedService){

    // Now we can access it here too!
    console.log( sharedService.helloWorld() );
}]);

Side note : Controllers should be capitalized to show their significance!

服务的力量:)

如果 controllerTwo 需要调用与 controllerOne 相同的函数,您可能需要创建一个服务来处理它。 Angular Services - 它们可以通过依赖注入在整个程序中访问。

var app = angular.module('myAppModule', [])
.controller('controllerOne', ['$scope', 'Hello', function($scope, Hello){
   console.log(Hello.helloWorld() + ' controller one');
}])
.controller('controllerTwo', ['$scope', 'Hello', function($scope, Hello){
   console.log(Hello.helloWorld() + ' controller two');
}])
.factory('Hello', [function() {
   var data = {
      'helloWorld': function() {
          return 'Hello World';
       }
   }

   return data;
}]);

希望对您有所帮助!

您需要使用 $controller 依赖项,您可以将一个控制器注入另一个控制器

.controller('controllerTwo', ['$scope', '$controller', function($scope, $controller){
  $controller('controllerOne', {$scope: $scope})
  //inside scope you the controllerOne scope will available
}]);

但更喜欢service/factory共享数据

你不能在另一个控制器中注入控制器,只有 serviceProviersinjectable。这就是你在控制器中作为未知提供者出错的原因一.

改用服务并将它们注入控制器,如果有一些功能可以在 controllers.Services 之间共享,这是在控制器之间共享数据的最佳方式。

您可以在 $rootScope 上声明变量或函数或 say 对象,它存在于您的整个应用程序中。

Share data between AngularJS controllers