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字段。但我可能是错的。 –