2015-03-02 45 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