0

我想弄清楚如何正確使用嵌套指令與transclusion和^要求角度。我想有一個outter指令有一個由嵌套的子指令更新的變量,但我希望所有的孩子都鏈接到該變量。我寫了一個很簡單的例子來說明這個問題帶有^ require的角度指令 - 訪問父範圍?

JS

(function() { 
    'use strict'; 

    angular 
     .module('app') 
     .directive('test', test); 

    function test() { 
     var directive = { 
      bindToController: true, 
      controller: testController, 
      'controllerAs': 'testController', 
      scope: {}, 
      templateUrl: 'scripts/test/test.html', 
      transclude: true 
     }; 
     return directive; 
    } 

    function testController() { 
     var self = this; 
     self.childCount = 0; 

     self.addChild = function addChild(child) { 
      self.childCount++; 
      child.childNumber = self.childCount; 
     } 
    } 

})(); 


(function() { 
    'use strict'; 

    angular 
     .module('app') 
     .directive('child', child); 

    function child() { 
     var directive = { 
      'scope': {}, 
      'link': link, 
      'templateUrl': 'scripts/test/child.html', 
      'transclude': true, 
      'require': '^test' 
     }; 
     return directive; 

     function link(scope, element, attrs, testController) { 
      scope.childNumber = null; 
      testController.addChild(scope); 
     } 

    } 

})(); 

主要HTML調用

<test> 
    <child></child> 
    <child></child> 
    <child></child> 
</test> 

的test.html部分

<h1>self.childCount = {{testController.childCount}}</h1> 
<div ng-transclude></div> 

child.html部分

<h3>I am child {{childNumber}} out of {{testController.childCount}}</h3> 

輸出(及發行)

self.childCount = 3 
I am child 1 out of 
I am child 2 out of 
I am child 3 out of 

正如你所看到的,child.html輸出不知道如何輸出{{testController.childCount }}。有什麼想法出錯?

回答

0

我通常不使用controllerAs語法,但也許嘗試從子範圍中刪除'scope': {}。這可能是通過創建隔離範圍,您的子指令無權訪問父控制器範圍。

+0

我明白你的意思是史蒂夫,但我試圖讓孩子的指令有一個孤立的範圍,以便他們可以知道他們是「孩子1出X」和「孩子2出X」。如果我沒有隔離範圍,那麼第一個變量(我在我的例子中稱爲childNumber)將被附加到父範圍,因此所有這些變量都會說「我是3中的3個孩子」 – mls3590712

+0

我的認爲childNumber字段是原型繼承的子作用域中的成員,因此只要在子作用域中聲明,每個子作用域都將擁有自己的childNumber字段。但我可能是錯的。 –