Angular 模块之间的依赖关系

Angular Dependencies Between Modules

我在使用模块之间的依赖注入时遇到问题。 我有一个模块实现了我需要在其他应用程序中使用的指令。

我在另一个应用程序声明中添加了此模块的依赖项,如下所示:

angular.module('mainApp', ['ngRoute', 'directiveApp']);

但是,在 directiveApp.controller 中实现的方法在 MainApp 的页面中似乎不可见,因为该指令无法 运行 其控制器所需的方法。

我知道这有点令人困惑,所以我在此 plunker 中举了一个例子来说明我面临的问题。

当你将另一个模块注入你自己的模块时,它实现的控制器和指令就可用了,但你需要正确使用它们。

你尝试的方法是不可能的,你可以这样做: http://plnkr.co/edit/peHH226vxtkI48RFZ3Eq?p=preview

  <body ng-controller="MainCtrl">
    <h1>Value: {{name}}!</h1>
    <button ng-click="mainModule()">Call a function in the main module!</button>

    <div ng-controller="SubCtrl">
      {{name}}
      <button ng-click="dependentModule()">Call a function in the dependent module!</button>
    </div>
  </body>

但请注意,您有两个不同的 $scopes,因此有两个不同的 name 变量。

这意味着您的 dependentModule() 函数属于您的 SubCtrl 并且您只能在它自己的 $scope

中使用它

不建议这样做,但如果确实需要,可以在自己的方法上使用其他控制器,然后复制结果:

http://plnkr.co/edit/ranK9n08NNVuSKIGX15G?p=preview

main.controller("MainCtrl", function($scope, $controller) {


  $scope.name = "Initial value";
  $scope.mainModule = function() {
    $scope.name = "a function in the same module";
  };

  $scope.bridgeFunction = function(){
    // Create a new scope
    var injectedScope = $scope.$new();

    // Use it on the other controller
    $controller('SubCtrl',{$scope : injectedScope });

    // Call the methdo on the controller
    testCtrl1ViewModel.dependentModule(); //And call the method on the newScope.

    // Copy the result from that scope into your own
    $scope.name = testCtrl1ViewModel.name;
  }

});

第三种选择是合并两个作用域,虽然这会变得非常混乱,但有可能:

http://plnkr.co/edit/1NKStMuYy0e00dhuWKUD?p=preview

main.controller("MainCtrl", function($scope, $controller) {

  $scope.name = "Initial value";

  //This can get very messy, but it is possible to merge the two scopes:
  $controller('SubCtrl',{$scope : $scope });

  $scope.mainModule = function() {
    $scope.name = "a function in the same module";
  };

});

希望对您有所帮助