2015-03-02 76 views
3

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

我从加入这个模块依赖于另一个应用程序的声明是这样的:

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

然而,落实到directiveApp.controller的方法,似乎不可见从MainApp的页面,因为指令无法从其控制器运行所需的方法。

我知道这有点令人困惑,所以我在这个plunker中举了一个例子,它显示了我正面临的问题。

+1

你不引用'SubCtrl'在模板中。所以,不会有'ng-click'方法绑定。 – 2015-03-02 23:01:37

+1

澄清上述评论,其中包括模块不会使所有内容在任何地方自动提供。你所做的只是让控制器可用。所以你仍然需要通过视图或路由将某个控制器包含进去。 – ribsies 2015-03-02 23:06:06

+0

正如我所提到的,subModule是关于一个指令。你是否可以在该指令中强制使用控制器(也许使用配置对象的控制器属性作为我的指令),而不是将指令嵌入到ng-controller中?我只是想知道是否可以使用这个指令更容易在其他应用程序中添加。这个指令是我组织中很多应用程序中的一个通用UI对象。我试图将它变成一个组件,我可以轻松地在任何这些应用程序中添加和使用它。 – 2015-03-03 04:56:48

回答

3

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

你正在尝试做的方式是不可能的,你可以做这样的事情: 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"; 
    }; 

}); 

希望帮助

+0

感谢人......第一个选项对我很好,虽然看起来很奇怪,但我可以参考DirectiveApp的控制器,因为我没有通过ng-app或bootstrap声明应用程序。我只能假定依赖注入使MainApp中的控制器可用。是这样的吗? – 2015-03-03 04:49:04